input 价格自动补全 vue项目中的实际运用


最近做到需要输入价格的项目,提出要求,需要自动补全后两位,也在网上查了许多,但是没找到很完美的,就参考着自己做了一版:

html:


              input
v-model="data.price"
@input="priceFormat(2)"
@blur="priceSave"
size="mini"
placeholder="请输入单价">
            

js:

methods: {
    //计算单价 decimal 为小数点后的精度
    priceFormat(decimal){
      var val = this.data.price
      val = val.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      val = val.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      val = val
        .replace('.', '$#$')
        .replace(/\./g, '')
        .replace('$#$', '.')
      switch (decimal) {
        case 1:
          val = val.replace(/^(-)*(\d+)\.(\d{1}).*$/, '$1$2.$3')
          break
        case 2:
          val = val.replace(/^(-)*(\d+)\.(\d{2}).*$/, '$1$2.$3')
          break
        case 3:
          val = val.replace(/^(-)*(\d+)\.(\d{3}).*$/, '$1$2.$3')
          break
        case 4:
          val = val.replace(/^(-)*(\d+)\.(\d{4}).*$/, '$1$2.$3')
          break
        case 5:
          val = val.replace(/^(-)*(\d+)\.(\d{5}).*$/, '$1$2.$3')
          break
        case 6:
          val = val.replace(/^(-)*(\d+)\.(\d{6}).*$/, '$1$2.$3')
          break
        case 7:
          val = val.replace(/^(-)*(\d+)\.(\d{7}).*$/, '$1$2.$3')
          break
        case 8:
          val = val.replace(/^(-)*(\d+)\.(\d{8}).*$/, '$1$2.$3')
          break
        case 9:
          val = val.replace(/^(-)*(\d+)\.(\d{9}).*$/, '$1$2.$3')
          break
        default:
          val = val.replace(/^(-)*(\d+)\.().*$/, '$1$2.$3')
          break
      }
      // 以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
      if (val.indexOf('.') < 0 && val != '') {
        if (val.length > 9) {
          val = val.substr(0, 9)
        }
        val = parseFloat(val)
      }else {
        const arr = val.split('.')
        if(arr[0].length > 0){
          arr[0] = parseFloat(arr[0])
        }else if(arr.length == 2 && arr[0] == '') {
          arr[0] = 0
        }
        val = arr.join('.')
      } 
      this.data.price = val
    },
    priceSave(){
      var val = this.data.price + ''
      if (val.indexOf('.') < 0 && val != '') {
        val = val + '.00'
      }else {
        const arr = val.split('.')
        if(arr.length == 2){
          if(arr[1] == ''){
            arr[1] = '00'
          }else if(arr[1].length == 1){
            arr[1] = arr[1] + '0'
          }
        }
        val = arr.join('.')
      }
      this.data.price = val
    },
}
这样基本上满足了所有要求,如果有什么不对的地方,或可以改进的地方,欢迎评论。