1. 全局注册自定义指令
- 在
main.js
中定义
Vue.directive('focus', {
inserted: function(el){
//el表示指令所绑定的元素
el.focus()
}
})
//在组件中使用
<input type="text" v-focus></input>
- 自定义指令传参 :
在main.js
中定义
Vue.directive('color', {
bind: function(el, binding){
//根据指令的参数设置背景颜色
el.style.backgroundColor = binding.value; //value就是绑定的值,是字符串red
}
})
//在组件中使用
<div v-color="color"></div>
data() {
return {
color:"red"
}
}
2.局部指令
组件中定义使用
<input type="text" v-focus></input>
directives: {
focus:{
inserted: function(el){
//el表示指令所绑定的元素
el.focus()
}
}
}
3.自定义指令钩子函数
钩子函数 :
- bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置
bind: (el, binding) => { }
- inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
inserted: (el) => { el.style.color = 'red'; }
- update:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。但是你可以通过比较更新前后的值来忽略不必要的模板更新 。
- componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
- unbind:只调用一次,指令与元素解绑时调用。
指令钩子函数会被传入以下参数
- el: 指令所绑定的元素,可以用来直接操作 DOM,就是放置指令的那个元素。
- binding: 一个对象,里面包含了几个属性
- vnode:Vue 编译生成的虚拟节点。
- oldVnode:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。