除了 Vue 内置的指令(如 v-if、v-for、v-bind),你还可以注册自定义指令。自定义指令主要用于对 DOM 元素进行底层操作,当内置指令无法满足需求时,自定义指令是很好的选择。
虽然 Vue 推荐使用组件和数据驱动视图,但有些场景需要直接操作 DOM:
这些功能如果封装成组件会显得过于复杂,用自定义指令更简洁。
<div id="app">
<input v-focus placeholder="自动聚焦">
</div>
<script>
Vue.directive('focus', {
inserted: function(el) {
el.focus()
}
})
new Vue({
el: '#app'
})
</script>
页面加载后,输入框会自动获得焦点。
Vue.directive('my-directive', {
bind: function(el, binding, vnode) {
// 指令绑定到元素时调用
},
inserted: function(el, binding, vnode) {
// 元素插入父节点时调用
},
update: function(el, binding, vnode, oldVnode) {
// VNode 更新时调用
},
componentUpdated: function(el, binding, vnode, oldVnode) {
// VNode 及其子 VNode 全部更新后调用
},
unbind: function(el, binding, vnode) {
// 指令与元素解绑时调用
}
})
new Vue({
el: '#app',
directives: {
'my-directive': {
bind: function(el, binding) {
// ...
}
}
}
})
如果只需要在 bind 和 update 时执行相同逻辑:
Vue.directive('color', function(el, binding) {
el.style.color = binding.value
})
// 注册时使用短横线命名
Vue.directive('my-directive', { /* ... */ })
// 使用时
<div v-my-directive></div>
Vue 2.6+ 支持动态指令参数:
<div v-mydirective:[argument]="value"></div>
<script>
Vue.directive('mydirective', {
bind: function(el, binding) {
console.log(binding.arg) // 参数名
console.log(binding.value) // 参数值
}
})
new Vue({
el: '#app',
data: {
argument: 'direction',
value: 'top'
}
})
</script>
何时使用指令:
何时使用组件: