使用vue自定义指令限制input输入内容为正整数

页面:

<input v-model="xxx" v-focus/>

方法:

directives: {
    // 注册一个局部的自定义指令 v-focus
    focus: {
      // 指令的定义
      inserted: function(el, validateStr) {
        el.addEventListener("input", function() {
          //进行验证
          checkedfun(el);
        });
        function checkedfun(el) {
          let reg = new RegExp("^[0-9]*$");
          if (!reg.test(el.value)) {
            el.value = el.value.replace(/[^0-9]+/g, "");
            el.dispatchEvent(new Event("input"));//调用input事件使vue v-model绑定更新
          }
        }
      }
    }
  }
原文地址:https://www.cnblogs.com/wxyz9527/p/13030683.html