自定义指令,禁止输入空格

91 阅读1分钟

禁止输入空格

修改绑定值

// v-no-space: 禁止输入空格
Vue.directive('no-space', {
  // 当被绑定的元素挂载到 DOM 中时……  
  inserted: function (el, binding, vnode) {
    el.addEventListener('input', function (event) {
      // 阻止空格字符的输入  
      if (event.target.value.includes(' ')) {  
        //移除空格,并更新输入框的值
        const newValue = event.target.value.replace(/\s/g, '');
        //更新显示值 dom
        event.target.value = newValue
        //更新显示值 v-model 绑定值
        vnode.data.model.callback(newValue)
      }  
    });  
  }
});

重点是更新v-model绑定值

vnode.data.model.callback(newValue)