vue 实现全局指令
注册全局指令
在Vue中,全局指令可以通过Vue.directive方法注册。该方法接受两个参数:指令名称和指令定义对象。指令定义对象包含一些钩子函数,如bind、inserted、update等,用于定义指令的行为。
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
使用全局指令
注册后的全局指令可以在任何组件的模板中使用。指令的使用方式是在元素上添加v-指令名。
<input v-focus>
指令钩子函数
指令定义对象可以包含多个钩子函数,用于在不同阶段执行逻辑。常用的钩子函数包括:

bind:指令第一次绑定到元素时调用。inserted:被绑定元素插入父节点时调用。update:所在组件的VNode更新时调用。componentUpdated:所在组件及其子组件的VNode全部更新后调用。unbind:指令与元素解绑时调用。
Vue.directive('demo', {
bind: function (el, binding, vnode) {
console.log('bind')
},
inserted: function (el, binding, vnode) {
console.log('inserted')
},
update: function (el, binding, vnode, oldVnode) {
console.log('update')
},
componentUpdated: function (el, binding, vnode, oldVnode) {
console.log('componentUpdated')
},
unbind: function (el, binding, vnode) {
console.log('unbind')
}
})
指令参数
指令可以接收参数,这些参数通过binding对象传递给钩子函数。binding对象包含以下属性:
name:指令名,不包括v-前缀。value:指令的绑定值。oldValue:指令绑定的前一个值。expression:字符串形式的指令表达式。arg:传给指令的参数。modifiers:一个包含修饰符的对象。
Vue.directive('color', {
bind: function (el, binding) {
el.style.color = binding.value
}
})
<p v-color="'red'">This text will be red.</p>
动态指令参数
指令的参数可以是动态的,通过方括号语法实现。

<p v-color:[dynamicColor]="'red'">This text will be dynamically colored.</p>
指令修饰符
修饰符是以点开头的特殊后缀,用于表示指令应该以某种特殊方式绑定。
Vue.directive('on', {
bind: function (el, binding) {
if (binding.modifiers.enter) {
el.addEventListener('keyup', function (event) {
if (event.keyCode === 13) {
binding.value()
}
})
}
}
})
<input v-on.enter="submit">
对象字面量
如果指令需要多个值,可以传入一个对象字面量。
Vue.directive('demo', {
bind: function (el, binding) {
console.log(binding.value.color) // => "white"
console.log(binding.value.text) // => "hello"
}
})
<div v-demo="{ color: 'white', text: 'hello' }"></div>
函数简写
如果指令的行为在bind和update时相同,可以简写为一个函数。
Vue.directive('color-swatch', function (el, binding) {
el.style.backgroundColor = binding.value
})
<div v-color-swatch="'#42b983'"></div>
全局指令的注意事项
全局指令会影响到所有Vue实例和组件,因此应当谨慎使用。如果指令只在特定组件中使用,建议使用局部指令。






