u-input输入小数限制只输入两位小数并且失去焦点自动补零
2022-12-02 本文已影响0人
扶得一人醉如苏沐晨
html
<u-form-item label="资产原值" prop="price" borderBottom>
<u--input border="none"
type="digit" @blur="priceBlur"
:maxlength="maxlength"
v-model="dataForm.price"
placeholder="请输入资产原值">
</u--input>
</u-form-item>
js中
写一个watch监听
watch: {
'dataForm.price': {
handler(val) {
if (!val) return;
if (val.includes('.')) {
//小数点后的位数
let numAfterDot = val.toString().split('.')[1].length;
//小数点前的位数
let numBeforeDot = val.toString().split('.')[0].length;
//最大长度等于小数点前的位数+3(小数点加小数点后两位)
this.maxlength = numBeforeDot + 3;
//小数点后的位数大于2,截取
if (numAfterDot > 2) {
this.dataForm.price = val.substr(0, numBeforeDot + 3);
}
} else {
//没有小数点不限制输入大小
this.maxlength = -1;
}
},
// 这个属性一定要加
immediate: true
}
},
//输入框失去焦点时触发
priceBlur() {
let val = this.dataForm.price;
console.log(val);
if (!val.includes('.')) {
this.dataForm.price += '.00';
} else if (val.includes('.')) {
let numDian = val.toString().split('.')[1].length;
if (numDian === 1) {
this.dataForm.price += '0';
}
}
},