vue el-input输入数字保留两位小数

情景:在多个input框中需要进行数据处理,绑定的数据值不同

在el-input中使用blur函数,里面在内置一个箭头函数可直接返回数据的方法

<el-input type="text" placeholder="请输入价格"
                         v-model="rangePrice_3"
                         oninput="value = value.replace(/[^\.\d]/g, '')"
                         @blur="()=>{rangePrice_3=keepTwoDecimalFull(rangePrice_3)}"
                         >
                         </el-input>

这样就可以避免再新建一个方法判断是哪一个input的数据变化

保留两位小数的代码无需改变添加,可保留在公共js中

keepTwoDecimalFull(num) {
    var result = parseFloat(num)
    if (isNaN(result)) {
      return ''
    }
    result = Math.round(num * 100) / 100
    var s_x = result.toString()
    var pos_decimal = s_x.indexOf('.')
    if (pos_decimal < 0) {
      pos_decimal = s_x.length
      s_x += '.'
    }
    while (s_x.length <= pos_decimal + 2) {
      s_x += '0'
    }
    return  s_x
  }

猜你喜欢

转载自blog.csdn.net/weixin_42574985/article/details/127423810