vue 限制表情输入

 在main.js中加入下列代码

import emoji   from './util/emoji'

Vue.directive('emoji',emoji)

vue 限制表情输入_第1张图片

 在util文件夹中加入emoji.js  下列代码

const findEle = (parent, type) => { 
        return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
      }
       
      const emoji = {
        bind(el, binding, vnode, oldVnode) {
          const regex = /(\ud83c[\udc00-\udfff])|(\ud83d[\udc00-\udfff])|(\ud83e[\udc00-\udfff])|[\u2100-\u32ff]|[\u0030-\u007f][\u20d0-\u20ff]|[\u0080-\u00ff]/g;
          const obj = findEle(el, 'input') || findEle(el, 'textarea');
          const zclearNoNum = function(e) {
            if (e.target.composing) return;
            const match = regex.exec(obj.value); 
            if (match) {
              /* for (let i=0;i {
              const match = regex.exec(obj.value);
              if (match) {
                obj.value = obj.value.replace(regex, '');
                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) {
            // console.log('按回车将字输入', e.target.value)
            e.target.composing = false
            obj.dispatchEvent(new Event('change'));
            setTimeout(() => {
              if (obj.value) {
                obj.value = obj.value.replace(regex, '');
                zclearNoNum(e);
              }
              // 触发v-model的更新
              obj.dispatchEvent(new Event('change'));
            }, 50)
          }
          obj.addEventListener('compositionstart', onCompositionStart)
          obj.addEventListener('compositionend', onCompositionEnd)
        },
        update(el, binding, vnode, oldVnode) {}
      }
      export default emoji

vue 限制表情输入_第2张图片 

 在输入框中加入  v-emoji

 

你可能感兴趣的:(vue.js,前端,javascript)