input只能保留两位小数

 <input style="width: 50px;" v-on:input="inputAlter(subV)"  type="text" v-model="goodsPrice">

方法1 使用正则

/^\d*(\.?\d{0,2})/g)[0]

方法2 字符判断

    inputAlter(val){
      let char = val.goodsPrice[val.goodsPrice.length-1]
      if ( 
        char === '0'||
        char === '1'||
        char === '2'||
        char === '3'||
        char === '4'||
        char === '5'||
        char === '6'||
        char === '7'||
        char === '8'||
        char === '9'
      ){
        if (char !== '0' && val.goodsPrice[val.goodsPrice.length-2] !== '.') {
          val.goodsPrice = (Math.floor(val.goodsPrice*100))/100
        }
      } else if (char === '.') {
        if (val.goodsPrice.indexOf('.') !== val.goodsPrice.length-1) {
          val.goodsPrice = val.goodsPrice.slice(0,val.goodsPrice.length-1)
        }
      } else {
        val.goodsPrice = val.goodsPrice.replace(char,'')
      }
      if (isNaN(val.goodsPrice)) val.goodsPrice = null
    }

前端小白大家多多指教

Logo

前往低代码交流专区

更多推荐