移动端通常对于input标签要求输入有一些校验,vue的指令可达到完美校验的作用

预期效果

<input v-model="times" :data-last_value="lastTimes" v-int v-max="8" v-min="2" />

属性data-last_value的值用来缓存用户输入框上一次失去焦点后输入的值,lastTimes是初始化的变量,后续不会再随意更改此值, v-model一定不要和data-last_value绑定同一个变量, 因为这样就起不到记住用户上一次输入值,并利用该值在校验不通过的情况下使用它

指令实现

以下3个指令可完全独立使用
  • 校验整数
  const util = {    isNumber(str) {       const num = Number(str);       return Math.floor(num) === num;    }  };  directives: {    int: {      inserted: (el) => {        let oldListener = el.onblur;        el.onblur = (e) => {          if (oldListener) {            oldListener(e);          }          const blurValue = Number(el.value);          // 用data-last_value属性值缓存上一次的值,以便恢复          const lastValue = el.getAttribute('data-last_value');          if (!util.isNumber(blurValue)) {            util.toast('请输入数字');            el.value = lastValue;            el.dispatchEvent(new Event('input'));          }          if (el.value === lastValue) return;          // 更新上一次的值          el.setAttribute('data-last_value', el.value);        }      },    },  }
  • 校验最小值
directives: {    min: {      inserted: (el, binding) => {        const oldListener = el.onblur;        el.onblur = (e) => {          if (oldListener) {            oldListener(e);          }          const blurValue = Number(el.value);          const min = binding.value;          if (blurValue < min) {            // util.toast替换成自己业务的toast提示弹窗            util.toast(`最小值不能小于${min}`);            el.value = min;            el.dispatchEvent(new Event('input'));          }          const lastValue = el.getAttribute('data-last_value');          if (el.value === lastValue) return;          // 更新上一次的值          el.setAttribute('data-last_value', el.value);        }      },    },  }
  • 校验最大值
  directives: {    max: {      // 指令的定义      inserted: (el, binding) => {        const oldListener = el.onblur;        el.onblur = (e) => {          if (oldListener) {            oldListener(e);          }          const blurValue = Number(el.value);          const max = binding.value;          if (blurValue > max) {            util.toast(`最大值不能大于${max}`);            el.value = max;            el.dispatchEvent(new Event('input'));          }          const lastValue = el.getAttribute('data-last_value');          if (el.value === lastValue) return;          // 更新上一次的值          el.setAttribute('data-last_value', el.value);        }      },    },  }

小小的校验指令没想到里面还有那么多细节~~~