<template> <div class="app-container"> <el-form :model="queryParams" ref="queryForm"…
- Usercode
- Assistant
- User
还是没效果,虽然显示修改成功,但是没有改变
- Assistant
还是没效果,虽然显示修改成功,但是没有改变
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['commSys:comm:add']"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['commSys:comm:edit']"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['commSys:comm:remove']"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['commSys:comm:export']"
>导出</el-button>
</el-col>
<el-col :span="1.5">
<el-button
:type="filterExpired ? 'danger' : 'danger'"
:plain="!filterExpired"
icon="el-icon-warning"
size="mini"
@click="toggleExpiredFilter"
v-hasPermi="['commSys:comm:filter']"
>{{ filterExpired ? '取消筛选' : '筛选过期' }}</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<div v-if="filterExpired" class="filter-notice">
当前显示过期商品共 {{ displayedCommList.length }} 条
</div>
<el-table v-loading="loading" :data="displayedCommList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键" align="center" prop="commId" />
<el-table-column label="商品名称" align="center" prop="commName" />
<el-table-column label="商品图片" align="center" width="120">
<template slot-scope="scope">
<img
:src="getImageUrl(scope.row.commImage)"
alt="商品图片"
class="comm-image"
@error="handleImageError(scope.$index)"
/>
</template>
</el-table-column>
<el-table-column label="规格(净含量)" align="center" prop="unit" />
<el-table-column label="商品价格" align="center" width="120">
<template slot-scope="scope">
<span class="price-display">¥{{ parseFloat(scope.row.price).toFixed(2) }}</span>
</template>
</el-table-column>
<el-table-column label="保质期" align="center" width="110">
<template slot-scope="scope">
<div class="expiration-display">
<span class="days">{{ scope.row.exp }}</span>
<span class="unit">个月</span>
</div>
</template>
</el-table-column>
<el-table-column label="商品类型" align="center" width="150">
<template slot-scope="scope">
<el-tag
:type="getClassTagType(scope.row.classId)"
effect="plain"
class="type-tag"
>
{{ getClassName(scope.row.classId) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="生产日期" align="center" prop="pd" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.pd, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column label="创建时间" align="center" prop="createTime" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<div class="operation-buttons">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
v-hasPermi="['commSys:comm:edit']"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
v-hasPermi="['commSys:comm:remove']"
>删除</el-button>
</div>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0 && !filterExpired"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="商品名称" prop="commName">
<el-input v-model="form.commName" placeholder="请输入商品名称" />
</el-form-item>
<el-form-item label="商品图片" prop="commImage">
<div v-if="form.commImage">
<img
:src="getImageUrl(form.commImage)"
alt="预览图"
class="preview-image"
@error="handleImageError(-1)"
/>
<el-button size="small" type="danger" @click="clearImage">移除图片</el-button>
</div>
<image-upload v-model="form.commImage" />
</el-form-item>
<el-form-item label="规格" prop="unit">
<el-input v-model="form.unit" placeholder="请输入规格" />
</el-form-item>
<el-form-item label="商品价格" prop="price">
<el-input
v-model.number="form.price"
placeholder="0.00"
style="width: 200px"
>
<template slot="prefix">¥</template>
</el-input>
</el-form-item>
<el-form-item label="保质期" prop="exp">
<el-input
v-model.number="form.exp"
placeholder="请输入月数"
style="width: 200px"
>
<template slot="append">个月</template>
</el-input>
</el-form-item>
<el-form-item label="商品类型" prop="classId">
<el-select
v-model="form.classId"
placeholder="请选择类型"
style="width: 100%"
>
<el-option
v-for="item in classList"
:key="item.classId"
:label="item.className"
:value="item.classId"
:style="{
color: getClassColor(item.classId),
fontWeight: 500
}"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="pd">
<el-date-picker
v-model="form.pd"
type="date"
value-format="yyyy-MM-dd"
placeholder="选择日期"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
帮修改一下,我想在添加商品或修改商品时,商品价格可以支持输入小数,然后显示出来,应该怎么做。给我完整代码,不要省略
你目前在模板中商品价格的输入框部分写的是:
<el-input
v-model.number="form.price"
placeholder="0.00"
style="width: 200px"
>
<template slot="prefix">¥</template>
</el-input>
v-model.number会自动对输入值进行强制转数字,导致输入小数点时困扰(比如输入12.时input会被自动转换成12,暂时不能输入小数点),这也是el-input限制输入类型为数字时常见的问题。
解决方案是使用el-input普通文本输入,配合自定义校验规则,允许输入符合正则表达式的金额格式,实现允许输入小数,并且显示时格式化为两位小数。
以下是根据你现有代码的完整代码,并修改了和price相关的地方,让输入支持小数,同时显示也格式化为两位小数:
el-input去掉了v-model.number,改成普通 v-model="form.price" ,绑定字符串。rules中添加价格的正则校验规则。parseFloat(...).toFixed(2)格式化,保持不变。<template>
<div class="app-container">
<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<el-form-item label="商品名称" prop="commName">
<el-input
v-model="queryParams.commName"
placeholder="请输入商品名称"
clearable
@keyup.enter.native="handleQuery"
/>
</el-form-item>
<el-form-item>
<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
</el-form-item>
</el-form>
<el-row :gutter="10" class="mb8">
<el-col :span="1.5">
<el-button
type="primary"
plain
icon="el-icon-plus"
size="mini"
@click="handleAdd"
v-hasPermi="['commSys:comm:add']"
>新增</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="success"
plain
icon="el-icon-edit"
size="mini"
:disabled="single"
@click="handleUpdate"
v-hasPermi="['commSys:comm:edit']"
>修改</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="danger"
plain
icon="el-icon-delete"
size="mini"
:disabled="multiple"
@click="handleDelete"
v-hasPermi="['commSys:comm:remove']"
>删除</el-button>
</el-col>
<el-col :span="1.5">
<el-button
type="warning"
plain
icon="el-icon-download"
size="mini"
@click="handleExport"
v-hasPermi="['commSys:comm:export']"
>导出</el-button>
</el-col>
<el-col :span="1.5">
<el-button
:type="filterExpired ? 'danger' : 'danger'"
:plain="!filterExpired"
icon="el-icon-warning"
size="mini"
@click="toggleExpiredFilter"
v-hasPermi="['commSys:comm:filter']"
>{{ filterExpired ? '取消筛选' : '筛选过期' }}</el-button>
</el-col>
<right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
</el-row>
<div v-if="filterExpired" class="filter-notice">
当前显示过期商品共 {{ displayedCommList.length }} 条
</div>
<el-table v-loading="loading" :data="displayedCommList" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" align="center" />
<el-table-column label="主键" align="center" prop="commId" />
<el-table-column label="商品名称" align="center" prop="commName" />
<el-table-column label="商品图片" align="center" width="120">
<template slot-scope="scope">
<img
:src="getImageUrl(scope.row.commImage)"
alt="商品图片"
class="comm-image"
@error="handleImageError(scope.$index)"
/>
</template>
</el-table-column>
<el-table-column label="规格(净含量)" align="center" prop="unit" />
<el-table-column label="商品价格" align="center" width="120">
<template slot-scope="scope">
<span class="price-display">¥{{ parseFloat(scope.row.price).toFixed(2) }}</span>
</template>
</el-table-column>
<el-table-column label="保质期" align="center" width="110">
<template slot-scope="scope">
<div class="expiration-display">
<span class="days">{{ scope.row.exp }}</span>
<span class="unit">个月</span>
</div>
</template>
</el-table-column>
<el-table-column label="商品类型" align="center" width="150">
<template slot-scope="scope">
<el-tag
:type="getClassTagType(scope.row.classId)"
effect="plain"
class="type-tag"
>
{{ getClassName(scope.row.classId) }}
</el-tag>
</template>
</el-table-column>
<el-table-column label="生产日期" align="center" prop="pd" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.pd, '{y}-{m}-{d}') }}</span>
</template>
</el-table-column>
<el-table-column label="创建时间" align="center" prop="createTime" width="180">
<template slot-scope="scope">
<span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
</template>
</el-table-column>
<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<template slot-scope="scope">
<div class="operation-buttons">
<el-button
size="mini"
type="text"
icon="el-icon-edit"
@click="handleUpdate(scope.row)"
v-hasPermi="['commSys:comm:edit']"
>修改</el-button>
<el-button
size="mini"
type="text"
icon="el-icon-delete"
@click="handleDelete(scope.row)"
v-hasPermi="['commSys:comm:remove']"
>删除</el-button>
</div>
</template>
</el-table-column>
</el-table>
<pagination
v-show="total>0 && !filterExpired"
:total="total"
:page.sync="queryParams.pageNum"
:limit.sync="queryParams.pageSize"
@pagination="getList"
/>
<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
<el-form-item label="商品名称" prop="commName">
<el-input v-model="form.commName" placeholder="请输入商品名称" />
</el-form-item>
<el-form-item label="商品图片" prop="commImage">
<div v-if="form.commImage">
<img
:src="getImageUrl(form.commImage)"
alt="预览图"
class="preview-image"
@error="handleImageError(-1)"
/>
<el-button size="small" type="danger" @click="clearImage">移除图片</el-button>
</div>
<image-upload v-model="form.commImage" />
</el-form-item>
<el-form-item label="规格" prop="unit">
<el-input v-model="form.unit" placeholder="请输入规格" />
</el-form-item>
<el-form-item label="商品价格" prop="price">
<el-input
v-model="form.price"
placeholder="0.00"
style="width: 200px"
@input="handlePriceInput"
>
<template slot="prefix">¥</template>
</el-input>
</el-form-item>
<el-form-item label="保质期" prop="exp">
<el-input
v-model.number="form.exp"
placeholder="请输入月数"
style="width: 200px"
>
<template slot="append">个月</template>
</el-input>
</el-form-item>
<el-form-item label="商品类型" prop="classId">
<el-select
v-model="form.classId"
placeholder="请选择类型"
style="width: 100%"
>
<el-option
v-for="item in classList"
:key="item.classId"
:label="item.className"
:value="item.classId"
:style="{
color: getClassColor(item.classId),
fontWeight: 500
}"
/>
</el-select>
</el-form-item>
<el-form-item label="生产日期" prop="pd">
<el-date-picker
v-model="form.pd"
type="date"
value-format="yyyy-MM-dd"
placeholder="选择日期"
/>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="primary" @click="submitForm">确 定</el-button>
<el-button @click="cancel">取 消</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import { listComm, getComm, delComm, addComm, updateComm } from "@/api/commSys/comm";
import { listClass } from "@/api/commSys/class";
export default {
name: "Comm",
data() {
return {
queryParams: {
pageNum: 1,
pageSize: 10,
commName: null
},
commList: [],
total: 0,
loading: false,
showSearch: true,
open: false,
title: "",
form: {
commId: null,
commName: null,
commImage: null,
unit: null,
price: '', // 改为字符串,初始空字符串
pd: null,
exp: null,
classId: null,
createTime: null,
updateTime: null
},
rules: {
commName: [
{ required: true, message: "请输入商品名称", trigger: "blur" }
],
price: [
{ required: true, message: "请输入商品价格", trigger: "blur" },
{ validator: (rule, value, callback) => {
const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
if (value === '' || value === null || value === undefined) {
callback(new Error('请输入商品价格'));
} else if (!reg.test(value)) {
callback(new Error('请输入有效的价格,最多两位小数'));
} else {
callback();
}
}, trigger: ['blur','change']}
],
classId: [
{ required: true, message: "请选择商品类型", trigger: "change" }
]
},
ids: [],
single: true,
multiple: true,
classList: [],
classColorMap: {
1: "#FF4757",
2: "#2ED573",
3: "#1E90FF",
4: "#FFA502"
},
imageBaseUrl: process.env.NODE_ENV === "development"
? "http://localhost:8080"
: "https://your-production-domain.com",
filterExpired: false
};
},
computed: {
displayedCommList() {
if (this.filterExpired) {
return this.commList.filter(item => this.isExpired(item));
}
return this.commList;
}
},
created() {
this.getList();
this.getClassList();
},
methods: {
getList() {
this.loading = true;
listComm(this.queryParams).then(response => {
this.commList = response.rows;
this.total = response.total;
this.loading = false;
});
},
getClassList() {
listClass().then(response => {
this.classList = response.rows;
});
},
cancel() {
this.open = false;
this.reset();
},
reset() {
this.form = {
commId: null,
commName: null,
commImage: null,
unit: null,
price: '', // 重置为字符串空
pd: null,
exp: null,
classId: null,
createTime: null,
updateTime: null
};
this.resetForm("form");
},
handleQuery() {
this.queryParams.pageNum = 1;
this.getList();
},
resetQuery() {
this.resetForm("queryForm");
this.handleQuery();
},
handleSelectionChange(selection) {
this.ids = selection.map(item => item.commId);
this.single = selection.length !== 1;
this.multiple = !selection.length;
},
handleAdd() {
this.reset();
this.open = true;
this.title = "添加商品";
},
handleUpdate(row) {
this.reset();
const commId = row.commId || this.ids;
getComm(commId).then(response => {
this.form = {
...response.data,
price: response.data.price != null ? response.data.price.toString() : '' // 转为字符串
};
this.open = true;
this.title = "修改商品";
});
},
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
// 转换价格字段为数字
let priceNum = parseFloat(this.form.price);
if (isNaN(priceNum)) {
this.$message.error('商品价格格式错误');
return;
}
// 赋值回form.price,保持数字格式
this.form.price = priceNum;
if (this.form.commId != null) {
updateComm(this.form).then(() => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
addComm(this.form).then(() => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
handleDelete(row) {
const commIds = row.commId || this.ids;
this.$modal.confirm(`是否确认删除商品编号为"${commIds}"的数据项?`).then(() => {
return delComm(commIds);
}).then(() => {
this.getList();
this.$modal.msgSuccess("删除成功");
}).catch(() => {});
},
handleExport() {
this.download("commSys/comm/export", {
...this.queryParams
}, `comm_${new Date().getTime()}.xlsx`);
},
getClassName(classId) {
const item = this.classList.find(item => item.classId === classId);
return item ? item.className : "";
},
getImageUrl(path) {
if (!path) return "https://picsum.photos/120/120?random=1";
if (path.startsWith("http")) return path;
return `${this.imageBaseUrl}${path}`;
},
handleImageError(index) {
console.error(`图片加载失败,索引: ${index}`);
},
clearImage() {
this.form.commImage = null;
},
getClassTagType(classId) {
const types = ["", "danger", "success", "info", "warning"];
return types[classId % 4 + 1] || "primary";
},
getClassColor(classId) {
return this.classColorMap[classId % 4 + 1] || "#57606f";
},
toggleExpiredFilter() {
this.filterExpired = !this.filterExpired;
this.handleSelectionChange([]);
},
isExpired(item) {
if (!item.pd || !item.exp) return false;
try {
const productionDate = new Date(item.pd);
if (isNaN(productionDate)) return false;
const expiryDate = new Date(productionDate);
expiryDate.setMonth(expiryDate.getMonth() + parseInt(item.exp));
return expiryDate < new Date();
} catch (e) {
console.error('日期计算错误:', e);
return false;
}
},
/**
* 可选:为了让用户输入价格时能够实时限制格式(只允许数字和一位小数点)
* 简单限制输入,非必需
*/
handlePriceInput(val) {
// 允许的格式是数字+0或1个小数点+最多2位小数
// 用正则替换多余字符,保持合法性,兼容用户编辑
let newVal = val.toString();
// 如果为空,允许直接赋值
if (newVal === '') {
this.form.price = '';
return;
}
// 允许负数的话,可以放开 -?,本案例无需求不支持负数
// 只允许数字和小数点,最多一位小数点
const reg = /^(\d+)?(\.)?(\d{0,2})?$/;
if (!reg.test(newVal)) {
// 格式错误,去掉最后一位
newVal = newVal.slice(0, -1);
}
// 只允许一个小数点
const firstDotIndex = newVal.indexOf('.');
if (firstDotIndex !== -1) {
const before = newVal.slice(0, firstDotIndex + 1);
// 去掉其他小数点
const after = newVal.slice(firstDotIndex + 1).replace(/\./g, '');
newVal = before + after;
}
this.form.price = newVal;
}
}
};
</script>
<style scoped>
.app-container {
padding: 20px;
}
.comm-image {
width: 80px;
height: 80px;
object-fit: cover;
border-radius: 4px;
border: 1px solid #ebeef5;
}
.preview-image {
max-width: 150px;
max-height: 150px;
margin-bottom: 10px;
display: block;
border-radius: 4px;
border: 1px solid #ebeef5;
}
.operation-buttons {
display: flex;
gap: 4px;
justify-content: center;
align-items: center;
white-space: nowrap;
}
.operation-buttons .el-button {
margin: 0;
padding: 0 4px;
}
.price-display {
color: #ff4500;
font-weight: 600;
font-size: 14px;
letter-spacing: 0.5px;
}
.expiration-display {
display: flex;
align-items: baseline;
justify-content: center;
}
.days {
font-size: 16px;
color: #2f3542;
margin-right: 3px;
}
.unit {
font-size: 12px;
color: #747d8c;
}
.type-tag {
min-width: 70px;
text-align: center;
letter-spacing: 0.5px;
border-radius: 12px;
transition: all 0.3s ease;
}
.type-tag:hover {
transform: scale(1.05);
}
.el-input__prefix {
display: flex;
align-items: center;
padding-left: 8px;
color: #606266;
}
.filter-notice {
margin: 10px 0;
padding: 10px;
background-color: #fffbe6;
border: 1px solid #ffe58f;
border-radius: 4px;
color: #faad14;
font-size: 14px;
}
</style>
form.price改为了字符串类型,方便输入。.toFixed(2) 保证两位小数显示。handlePriceInput 方法做简单输入限制,过滤非法输入字符,增强体验(此可选,若不需要可以去掉)。这样就可以在添加和修改商品时输入小数价格,并正确显示了。若你用的Element UI版本支持input事件的 .native修饰,可以自行调整。---
如果你还有其它需求欢迎继续提问!
你的问题是:提交表单时虽然显示“修改成功”,但商品价格没有变化。这种情况通常是因为:
price 仍然是字符串,提交给后端时没有按数字格式提交price 时未更新数据结合你现有代码和描述,我帮你找到了两个可能的原因与对应改进方案:
price 是数字类型你目前转换了 this.form.price 为数字,但updateComm的调用是否使用了最新的对象?
请改为这样:
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
// price 字符串转数字
const priceNum = parseFloat(this.form.price);
if (isNaN(priceNum)) {
this.$message.error('商品价格格式错误');
return;
}
const submitData = {
...this.form,
price: priceNum
};
if (submitData.commId != null) {
updateComm(submitData).then(() => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
addComm(submitData).then(() => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
注意这里用了 submitData,不直接修改this.form.price,避免某些响应式未更新问题。
price,类型是否是数字确保接口中 price 字段是数字格式,后端能正确更新。
handleUpdate赋值时,确保price赋值成字符串类型,否则后续输入会有问题handleUpdate(row) {
this.reset();
const commId = row.commId || this.ids;
getComm(commId).then(response => {
this.form = {
...response.data,
price: response.data.price != null ? response.data.price.toString() : ''
};
this.open = true;
this.title = "修改商品";
});
},
之前给你的正则可以匹配到最多2位小数:
const reg = /^(0|[1-9]\d*)(\.\d{1,2})?$/;
但是为了更宽松,你可以用:
const reg = /^\d+(\.\d{1,2})?$/;
并且需要对空字符做特殊判断。
你可以直接替换原有的submitForm和handleUpdate方法为以下代码:
handleUpdate(row) {
this.reset();
const commId = row.commId || this.ids;
getComm(commId).then(response => {
this.form = {
...response.data,
price: response.data.price != null ? response.data.price.toString() : ''
};
this.open = true;
this.title = "修改商品";
});
},
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
const priceNum = parseFloat(this.form.price);
if (isNaN(priceNum)) {
this.$message.error('商品价格格式错误');
return;
}
// 组合新数据对象,避免直接改form.price
const submitData = {
...this.form,
price: priceNum
};
if (submitData.commId != null) {
updateComm(submitData).then(() => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
addComm(submitData).then(() => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
在submitForm调用前加个console.log(submitData)看看price是不是正确。
<el-form-item label="商品价格" prop="price">
<el-input
v-model="form.price"
placeholder="0.00"
style="width: 200px"
@input="handlePriceInput"
>
<template slot="prefix">¥</template>
</el-input>
</el-form-item>
data() {
return {
form: {
/* 其他字段 */
price: '', // 字符串类型,初始空字符串
/* 其他字段 */
},
rules: {
price: [
{ required: true, message: "请输入商品价格", trigger: "blur" },
{ validator: (rule, value, callback) => {
const reg = /^\d+(\.\d{1,2})?$/;
if (value === '' || value === null || value === undefined) {
callback(new Error('请输入商品价格'));
} else if (!reg.test(value)) {
callback(new Error('请输入有效的价格,最多两位小数'));
} else {
callback();
}
}, trigger: ['blur', 'change'] }
],
/* 其他规则 */
}
};
},
methods: {
handleUpdate(row) {
this.reset();
const commId = row.commId || this.ids;
getComm(commId).then(response => {
this.form = {
...response.data,
price: response.data.price != null ? response.data.price.toString() : ''
};
this.open = true;
this.title = "修改商品";
});
},
submitForm() {
this.$refs["form"].validate(valid => {
if (valid) {
const priceNum = parseFloat(this.form.price);
if (isNaN(priceNum)) {
this.$message.error('商品价格格式错误');
return;
}
const submitData = {
...this.form,
price: priceNum
};
if (submitData.commId != null) {
updateComm(submitData).then(() => {
this.$modal.msgSuccess("修改成功");
this.open = false;
this.getList();
});
} else {
addComm(submitData).then(() => {
this.$modal.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
}
});
},
// (可选) 输入限制函数,防止输入错误,但不是必须
handlePriceInput(val) {
if (val === '') {
this.form.price = '';
return;
}
const reg = /^\d*\.?\d{0,2}$/;
if (!reg.test(val)) {
this.form.price = val.slice(0, -1);
}
},
/* 其他方法 */
}
price字段作为字符串存储,验证时用正则匹配,以便支持小数点输入updateComm和addComm方法使用转换后的数字字段handleUpdate中给表单赋值时,将原本数字转为字符串,避免影响input输入体验如果你依然有问题,可以把改动后提交的数据打印出来和后端日志做对比,我可以帮你分析。祝你成功!
Not yet included in a published release.