vue的指令实现
Vue 指令的实现
Vue 指令是一种特殊的属性,用于在 DOM 元素上应用特定的行为。Vue 提供了一些内置指令(如 v-model、v-if),同时也支持自定义指令的实现。
内置指令的常见用法
v-model 实现双向数据绑定:
<input v-model="message" />
<p>{{ message }}</p>
v-if 和 v-show 控制元素显示:
<div v-if="isVisible">显示内容</div>
<div v-show="isActive">动态显示</div>
v-for 实现列表渲染:
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
自定义指令的实现
注册全局自定义指令:
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
注册局部自定义指令:
new Vue({
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
})
使用自定义指令:
<input v-focus />
指令的钩子函数
bind:只调用一次,指令第一次绑定到元素时调用。
bind: function(el, binding, vnode) {
// 初始化设置
}
inserted:被绑定元素插入父节点时调用。
inserted: function(el, binding, vnode) {
// DOM 操作
}
update:所在组件的 VNode 更新时调用。

update: function(el, binding, vnode, oldVnode) {
// 响应式更新
}
componentUpdated:所在组件及子组件 VNode 全部更新后调用。
componentUpdated: function(el, binding, vnode, oldVnode) {
// 完成更新后的操作
}
unbind:只调用一次,指令与元素解绑时调用。
unbind: function(el, binding, vnode) {
// 清理工作
}
指令参数传递
静态值传递:
<div v-demo="'fixed-value'"></div>
动态值传递:
<div v-demo="dynamicValue"></div>
参数对象传递:

Vue.directive('demo', {
bind: function(el, binding) {
console.log(binding.value) // 指令的绑定值
console.log(binding.oldValue) // 前一个值
console.log(binding.arg) // 参数
console.log(binding.modifiers) // 修饰符对象
}
})
指令修饰符
带修饰符的指令:
<div v-demo.slow="msg"></div>
处理修饰符:
Vue.directive('demo', {
bind: function(el, binding) {
if (binding.modifiers.slow) {
// 慢速动画处理
}
}
})
函数简写
当只需要 bind 和 update 钩子时可以使用简写:
Vue.directive('color', function(el, binding) {
el.style.color = binding.value
})
对象字面量
传递多个值:
<div v-demo="{ color: 'white', text: 'hello' }"></div>
处理对象值:
Vue.directive('demo', {
bind: function(el, binding) {
console.log(binding.value.color) // "white"
console.log(binding.value.text) // "hello"
}
})
动态指令参数
动态参数名:
<div v-[direction]="200"></div>
data: {
direction: 'left'
}






