Fork me on GitHub

vue自定义指令过滤特殊字符

 1.新建inputFilter.js文件  

const addListener = function(el,type,fn) {
   el.addEventListener(type,fn,false);    
}
const specialFilter = function(el) {
   addListener(el, 'keyup', () =>{
       let reg = /[^\a-\z\A-\Z0-9\s\U4E00-\U9FA5]/g;
       let enLanguage = "Special characters are not allowed";
       let zhLanguage = "不允许出现特殊字符";
       let language = localStorage.language == 'ch' ? zhLanguage : enLanguage;//中英文判断
      if(reg.test(el.value)){
           if(document.getElementByClassName('el-message').length ==0){//防止提示信息同时多次出现
               Vue.prototype.tips = Vue.prototype.$message({
                   showClose: true,
                   message: language,
                   type: 'warning'
               });
           }
      }else{
           Vue.prototype.tips.close();
           Vue.prototype.tips = Vue.prototype.$message({
                   showClose: true,
                   message: language,
                   type: 'warning'
           });
      }
      el.value = el.value.replace(/[^\a-\z\A-\Z0-9\s\U4E00-\U9FA5]/g,'');  
   });
}
export default {
    bind(el, binding){
        if(el.tagName.toLowerCase() !== 'input'){    
             el = el.getElementsByTagName('input')[0];
        }
        switch(binding.arg){
            case 'special': 
                 specialFilter(el);
                 break;
            default: 
                 break;
        }
    }
}    

2.新建index.js

import inputFilter from './inputFilter'
const install = function(Vue){
    Vue.directive('inputFilter', iniputFilter);
};
if(window.Vue){
    window.inputFilter = inputFilter;
    Vue.use(install);
}
inputFilter.install  = install;
export default inputFilter;

3.main.js

//main.js中引入index.js文件
import inputFilter from './lib/filter/index'
//注册一个全局自定义指令
Vue.directive(inputFilter);

4.使用

<el-input v-model="keywords" :placeholder="$t('label.queryMirrorName')" size="small" v-input-filter:special clearable></el-input>

 

posted on 2020-08-24 19:29  蓝魂殇  阅读(2415)  评论(1编辑  收藏  举报

导航