当前位置: 首页 > 工具软件 > emoji-regex > 使用案例 >

vue通过自定义组件禁止input输入框输入emoji表情

漆雕兴平
2023-12-01

首先封装好js文件,代码如下,如需自取:

import emojiRegex from 'emoji-regex';  //npm install emoji-regex
import Vue from 'vue';
Vue.directive('clearEmoji', {
  bind(el, binding, vnode, oldVnode) {
    const regex = emojiRegex();
    const obj = el.querySelectorAll('.el-input__inner,.el-textarea__inner')[0];
    let zclearNoNum = function (e) {
      if(e.target.composing) return;
      let match = regex.exec(obj.value); //也可以直接用正则表达式判断
      if(match) {
        /*for (let i=0;i<match.length;i++) {
          obj.value = obj.value.replace(match[i],"");
        }*/
        obj.value = obj.value.replace(/(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g, "");
        zclearNoNum(e);
      }
      // 触发v-model的更新
      obj.dispatchEvent(new Event('input'));
    }
    let zblur = function (e) {
      zclearNoNum(e);
      setTimeout(()=>{
        let match = regex.exec(obj.value);
        if(match) {
          obj.value = obj.value.replace(/(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g, "");
          zclearNoNum(e);
        }
        // 触发v-model的更新
        obj.dispatchEvent(new Event('change'));
      }, 50)
    }
    obj.onkeyup = zclearNoNum;
    obj.onblur = zblur;

    function onCompositionStart (e) {
      e.target.composing = true
    }
    function onCompositionEnd (e) {
      e.target.composing = false
      obj.dispatchEvent(new Event('keyup'));
    }
    // https://segmentfault.com/a/1190000009246058
    obj.addEventListener('compositionstart', onCompositionStart)
    obj.addEventListener('compositionend', onCompositionEnd)
  },
  update(el, binding, vnode, oldVnode) {}
})

然后在main.js中全局引入即可

import '../src/components/clearEmoji'
 类似资料: