问题:今天做输入框校验金额,要求:小数点后只能输入两位,
借鉴了网上大神之后,发现实现不了,value值始终无法赋值给 price,代码如下
//type=digit 弹出带小数点的数字键盘
<input type="digit" placeholder="请输入金额" v-model="price" @input="inputChange" />
inputChange(){
let value = this.price.toString();
value = value.replace(/[^\d.]/g,"");//清除"数字"和"."以外的字符
value = value.replace(/^\./g,"");//验证第一个字符是数字而不是字符
value = value.replace(/\.{2,}/g,".");//只保留第一个.清除多余的
value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数
console.log(value);//校验值完全没有问题
this.price = value; //赋值却赋不上
},
解决办法:
inputChange(){
let value = this.price.toString();
value = value.replace(/[^\d.]/g,"");
value = value.replace(/^\./g,"");
value = value.replace(/\.{2,}/g,".");
value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
// 看这里!!!
this.$nextTick(() => {
this.price = value;
})
},
具体原因参考大神文章:走你
另一种校验写法:
!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(this.price)