
https://blog.51cto.com/zhengys/6991950
新建一个工具类
//special.js
import Vue from 'vue';
// 禁止输入特殊字符
Vue.directive('special', {
bind: function (el, binding, vnode) {
// 正则规则可根据需求自定义
// const regRule = /[`~^!@#$€£₤%^&*()_\-+=<>?:"{}|.\/;'\\[\]·~!……@#¥¥%*()\-+={}|《》?:“”【】‘']/im;
const regRule = /[<>"'=?!\/\\]/im;
let $inp = findEle(el, 'input') || findEle(el, 'textarea');
el.$inp = $inp;
$inp.handle = function (event) {
let val = $inp.value;
$inp.value = val.replace(regRule, '');
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);
}
引入工具类
//在main.js中引入
import '@/utils/special'
使用
//在input中直接使用v-special
<el-input v-model="xx" v-special />