需要: input输入框只能输出纯数字、小数。小数点后保留几位不做限度

废话: 参考了一大堆解决方案后,没有一个能满足我以后的业务需要,故做个记录

思路: 监听input事件,而后用正则过滤掉不合乎需要的值即可

// limit-function.js 文件    import Vue from "vue";     let v = new Vue();    export default {     /**       * 只能输出数字(小数点)       */      inputDigit(value) {          // 定义一个正则:只承受如下模式例子: 3.1235 5.1354           // 此正则不对小数长度做限度          let digitReg = /^\d+(\.\d+)?$/;          // 步骤一: 将输出的值宰割成一个一个的字符          let strList = value.split("");          let newValue = "";          // 步骤二: 遍历字符数组,判断每个字符是否合乎冀望          for (let item of strList) {              if (isNaN(item - 0)) {                  if (item === ".") {                      newValue += item;                  }              } else if (/\d/g.test(item)) {                  newValue += item;              }          }          // 步骤三: 对曾经合乎冀望的字符进行最初的格局验证          // 因为有可能存在 2.323.32.. 这种多个小数点的状况,所以要再次验证          if (!digitReg.test(newValue)) {              let strs = newValue.split(".");              if (strs.length > 1) {                  newValue = strs[0] + "." + strs[1];              }          }          return newValue;      }    }

vue2组件中应用办法

// main.js中绑定这个limit-function到vue原型对象上,供全局应用import limit from "./utils/limit-fuction";Vue.prototype.$limit = limit;
<el-input     v-model="obj.num"      @input="(e) => (obj.num = $limit.inputDigit(e))"  ></el-input>