vue指令实现
Vue 指令的实现方式
Vue 指令是特殊的标记,用于在 DOM 元素上应用特定的行为。可以通过全局或局部方式注册自定义指令。
全局注册指令
在 Vue 应用中通过 Vue.directive 方法全局注册指令:
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
使用指令时在模板中添加 v-focus:
<input v-focus>
局部注册指令
在组件选项中通过 directives 属性局部注册指令:
export default {
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
}
指令钩子函数
自定义指令可以包含以下钩子函数:
bind:指令第一次绑定到元素时调用inserted:被绑定元素插入父节点时调用update:所在组件的 VNode 更新时调用componentUpdated:所在组件及子组件 VNode 全部更新后调用unbind:指令与元素解绑时调用
Vue.directive('demo', {
bind: function (el, binding, vnode) {
// 初始化设置
},
update: function (el, binding, vnode) {
// 根据绑定值的变化更新行为
}
})
指令参数
钩子函数接收以下参数:
el:指令绑定的元素binding:包含指令信息的对象vnode:Vue 编译生成的虚拟节点
binding 对象包含以下属性:
name:指令名(不包含 v- 前缀)value:指令的绑定值oldValue:指令绑定的前一个值expression:字符串形式的指令表达式arg:传给指令的参数modifiers:包含修饰符的对象
动态指令参数
指令的参数可以是动态的:
<div v-demo:[direction]="200"></div>
Vue.directive('demo', {
bind: function (el, binding) {
// direction 将作为 binding.arg 传递
el.style.position = 'fixed'
const s = binding.arg || 'top'
el.style[s] = binding.value + 'px'
}
})
函数简写
当需要在 bind 和 update 中触发相同行为时,可以使用简写函数:
Vue.directive('color', function (el, binding) {
el.style.color = binding.value
})
对象字面量
如果指令需要多个值,可以传入对象字面量:
<div v-demo="{ color: 'white', text: 'hello' }"></div>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // "white"
console.log(binding.value.text) // "hello"
})






