el-input添加自定义指令只允许输入中文/英文/数字,兼容输入法事件

省流

script:

directives: {
 regexp: {
   inserted: (el, binding, vnode) => {
     let composition = false
     const formatValue = function (e) {
       if (composition) return
       // vnode.componentInstance组件实例
       vnode.componentInstance.$emit('input', e.target.value.replace(/[^\u4e00-\u9fa5a-zA-Z0-9/]/g, ''))
     }
     el.oninput = formatValue
     // 请务必使用addEventListenner,不信邪你试试el.oncompositionstart
     el.addEventListener('compositionstart', () => { composition = true })
     el.addEventListener('compositionend', e => {
       composition = false
       formatValue(e)
     })
   }
 }
}

template:

<el-input v-regexp />

有问题欢迎指出

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