要求
- 只能输入数字
- 最多一个小数点
代码
<Input type="text" v-model="ipt" />
that.$nextTick(() => {
if(this.ipt) {
// 如果输入的有字符串,把字符串转化为数字
if(/[^\d\.]/.test(that.ipt)) {
that.ipt= that.ipt.replace(/[^\d\.]/g, '');
}
// 如果输入了多个小数点
if(that.ipt.split('.').length > 2) {
that.ipt= that.ipt.split('.')[0] + '.' + that.ipt.split('.')[1];
}
// 如果和上一次的值相等,就不处理
// if(Number(that.ipt) == Number(that.iptOrigin)) {
// return;
// }
}
})
// 如果把数据删了,过一会再赋值,因为万一是删掉输入0.5呢
settimeout(() => {
// 如果把值删了
if(!that.ipt) {
that.ipt= 1; // 初始值
}
if(that.ipt == '.') {
that.ipt= 1
}
}, 1500)
一定要放到nexttick里面!