vue通过自定义指令实现文本框只能输入正整数

directives: {
    numInput(el) {
      el.addEventListener("keypress", function (e) {
        e = e || window.event;
        let charcode = typeof e.charCode === "number" ? e.charCode : e.keyCode;
        let re = /\d/;
        if (
          !re.test(String.fromCharCode(charcode)) &&
          charcode > 9 &&
          !e.ctrlKey
        ) {
          if (e.preventDefault) {
            e.preventDefault();
          } else {
            e.returnValue = false;
          }
        }
      });
    },
  },

使用

 <input type="text" v-numInput  />

你可能感兴趣的:(vue,vue.js)