1.給input綁定keyup函數:
<input
type="text"
class="form-control"
id="inputEmail3"
v-model="price"
placeholder="請輸入價格"
@keyup="priceFormat"
/>
2.編寫priceFormat函數:
priceFormat(){
//非數字和小數點去掉
this.price=this.price.replace(/[^0123456789.]/,"")
//之前沒注意寫錯了!!!!
//防止無輸入無限個“.”
this.price=this.price.replace(/\.+/ ,".")
//在不是“0.”開頭的字符進行修改:“01”=>1
if(this.price.charAt(0)=="0"&&this.price.charAt(1)!="."&&this.price.length>=2){
this.price=this.price.replace(/0/ ,"")
}
//獲取第一個小數點的索引值
var index=this.price.indexOf('.')
//獲取最后一個小數點的索引值
var lastIndex=this.price.lastIndexOf('.')
//判斷小數點是不是開頭,如果是開頭,則去除
if(index==0){
this.price=this.price.replace(/\./ ,"")
}
//只允許小數點后面有2位字符
if(index>=1){
this.price=this.price.substring(0,index+3)
}
//防止小數點后面又出現小數點
if(index!=lastIndex){
this.price=this.price.substring(0,index+2)
}
}
