問題:今天做輸入框校驗金額,要求:小數(shù)點后只能輸入兩位富岳,
借鑒了網(wǎng)上大神之后器赞,發(fā)現(xiàn)實現(xiàn)不了,value值始終無法賦值給 price启搂,代碼如下
//type=digit 彈出帶小數(shù)點的數(shù)字鍵盤
<input type="digit" placeholder="請輸入金額" v-model="price" @input="inputChange" />
inputChange(){
let value = this.price.toString();
value = value.replace(/[^\d.]/g,"");//清除"數(shù)字"和"."以外的字符
value = value.replace(/^\./g,"");//驗證第一個字符是數(shù)字而不是字符
value = value.replace(/\.{2,}/g,".");//只保留第一個.清除多余的
value = value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能輸入兩個小數(shù)
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');
// 看這里!8於摹牢撼!
this.$nextTick(() => {
this.price = value;
})
},
具體原因參考大神文章:走你
另一種校驗寫法:
!/^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/.test(this.price)