https://cn.vuejs.org/v2/guide/custom-directive.htmlhtml
這裏須要用到的是對傳入的binding的參數進行dom操做,將組件中的vue實例傳入,改變vue實例中data的值vue
import Vue from 'vue'; import { Message } from 'element-ui' // 過濾輸入框表情 Vue.directive('noEmoji', { bind: function (el) { console.log(el, 'bind') }, inserted: function (el) { console.log(el, 'inserted') }, update: function clearEmoji(el, binding, vnode, oldVnode) { let emojiRegex = require('emoji-regex') let regex = emojiRegex() let match = regex.exec(el.value) if(match) { Message('此輸入框不支持表情') el.value = el.value.replace(match[0], "") if (binding && binding.value) { let vm = binding.value.vm let attr = binding.value.attr let length = attr.length switch (length) { case 1: vm.$set(vm, attr[0], el.value); break; case 2: vm.$set(vm[attr[0]], attr[1], el.value); break; default: return false } } clearEmoji(el) } }, componentUpdated: function(el, binding, vnode, oldVnode) { console.log(el, 'componentUpdated') }, unbind: function(el, binding, vnode, oldVnode) { console.log(el, 'unbind') }, })
這個指令只支持原生的dom,對於el-input這樣的UI組件標籤失效,由於自定義指令沒有辦法改變el-input標籤的domnode