正常校验效果如下(修改后的代码了)
博主遇到了一个小问题,但觉得可以记录,避免以后继续踩坑,很疑惑明明相加已经是1了
如图所示,做了个小功能,价格比例这一列校验所有行相加为1的行上校验
校验规则代码如下
写在computed是为了实时填写的时候触发校验规则更新校验是否正确
computed: {
rules() {
var testValid = (rule, value, callback) => {
if (value <= 0) {
return callback(new Error('不能填写小于等于0的数据'))
}
let flag = false
let countArr = []
if (this.list && this.list.length > 0) {
this.list.forEach((item) => {
if (item.priceRatio) {
countArr.push(item.priceRatio)
}
})
}
const sum = (num) => {
let i = 0,
result = 0
while (i < num.length) {
result += Number(num[i])
i++
}
return result
}
const sumlength = (num) => {
let i = 0
while (i < num.length) {
i++
}
return i
}
let count = sum(countArr)
let currentLength = sumlength(countArr)
console.log('currentLength', currentLength)
console.log('count', count)
if ((count != 1 && currentLength == this.list.length) || count > 1) {
flag = true
}
if (flag) {
callback(new Error('价格比例相加不等于1'))
} else {
this.$refs['tabs'].clearTableValidate()
callback()
}
}
return {
// 主表表单校验规则
goodsCode: [
{ required: true, message: '此项为必填项', trigger: 'blur' },
],
priceRatio: [
{
required: this.isRequired,
message: '此项为必填项',
trigger: ['blur', 'change'],
},
{
validator: this.isRequired ? testValid : '',
trigger: ['blur', 'change'],
},
],
giftQuantity: [
{ required: false, trigger: 'blur' },
{
pattern: /^([1-9][0-9]*)$/,
message: '请输入正整数',
trigger: 'blur',
},
],
quantity: [
{ required: true, message: '此项为必填项', trigger: 'blur' },
{
pattern: /^(0|\+?[1-9][0-9]{0,4})$/,
message: '请输入不超过五位数的正整数',
trigger: 'blur',
},
],
}
},
为此,我打印了一下对应相加数据,发现相加竟然是0.99999,焕然大悟就是存在了精度丢失问题,为此只需要改造
const sum = (num) => {
let i = 0,
result = 0
while (i < num.length) {
result += Number(num[i])
i++
}
return Number(result.toFixed(2)) // 将结果四舍五入到2位小数 解决精度丢失问题
}
即可大功告成解决这个小问题