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)
}
}