介绍:无入侵的输入检测,感觉是比较优雅的解决问题
关键点:
1.正则要写对,正则匹配的值需确认无误
2.重新触发双向绑定的方式
import Vue from 'vue'
// 禁止输入特殊字符
Vue.directive('disable-synmol', {
bind: function (el, binding, vnode) {
// 正则规则可根据需求自定义
// /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~!@#¥%……&*()——\-+={}|《》?:“”【】、;‘',。、]/im;
const regRule = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~!@#¥%……&*()——\-+={}|《》?:“”【】、;‘',。、]/im
let $inp = findEle(el, 'input')
el.$inp = $inp
$inp.handle = function (event) {
let val = $inp.value
$inp.value = val.replace(regRule, '')
// event.target.value = $inp.value
// binding.value = $inp.value
// this.value = $inp.value
// console.info('disable-synmol $inp', $inp)
// console.info('disable-synmol $inp.value ', $inp.value)
// console.info('disable-synmol binding', binding)
//调用input事件使vue v-model绑定更新
// $inp.dispatchEvent(new Event('input'))
// event.target.dispatchEvent(new Event('input'))
trigger($inp, 'input')
}
$inp.addEventListener('keyup', $inp.handle)
},
unbind: function (el) {
el.$inp.removeEventListener('keyup', el.$inp.handle)
}
})
const findEle = (parent, type) => {
return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
}
const trigger = (el, type) => {
const e = document.createEvent('HTMLEvents')
e.initEvent(type, true, true)
el.dispatchEvent(e)
}
参考资料:
Vue全局解决限制input输入表情和特殊字符方案 - 梓鹏 - 博客园
input输入框限制输入特殊字符_Small_Pang的博客-CSDN博客
Vue input 控件: 通过自定义指令(directive)使用正则表达式限制input控件的输入 - 两轮明月 - 博客园