1.什么是自定义指令
vue 官方提供了 v-text、v-for、v-model、v-if 等常用的指令。除此之外 vue 还允许开发者自定义指令。
2.自定义指令的分类
vue 中的自定义指令分为两类,分别是:
⚫ 私有自定义指令
⚫ 全局自定义指令
3.私有自定义指令
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令。示例代码如下:
directives: {
// 定义名为 color 的指令,指向一个配置对象
color: {
bind(el) {
el.style.color = 'red'
}
}
}
4.使用自定义指令
在使用自定义指令时,需要加上 v- 前缀。示例代码如下:
<h1 v-color>App 根组件</h1>
5.为自定义指令动态绑定参数值
在 template 结构中使用自定义指令时,可以通过等号(=)的方式,为当前指令动态绑定参数值:
<h1 v-color="color">App 根组件</h1>
data() {
return {
color: 'blue'
}
}
6.通过 binding 获取指令的参数值
在声明自定义指令时,可以通过形参中的第二个参数,来接收指令的参数值:
directives: {
// 定义名为 color 的指令,指向一个配置对象
color: {
// 当指令第一次被绑定到元素上的时候,会立即触发 bind 函数
// 形参中的 el 表示当前指令所绑定到的那个 DOM 对象
bind(el, binding) {
console.log('触发了 v-color 的 bind 函数')
el.style.color = binding.value
}
}
}
7.update 函数
bind 函数只调用 1 次:当指令第一次绑定到元素时调用,当 DOM 更新时 bind 函数不会被触发。 update 函数会在每次 DOM 更新时被调用。示例代码如下:
directives: {
// 定义名为 color 的指令,指向一个配置对象
color: {
bind(el, binding) {
console.log('触发了 v-color 的 bind 函数')
el.style.color = binding.value
},
// 在 DOM 更新的时候,会触发 update 函数
update(el, binding) {
console.log('触发了 v-color 的 update 函数')
el.style.color = binding.value
}
}
}
8.函数简写
如果 bind和update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写成函数格式:
directives: {
color(el, binding) {
el.style.color = binding.value
}
}
9.全局自定义指令
全局共享的自定义指令需要通过“Vue.directive()”进行声明,示例代码如下:
Vue.directive('color', function(el,binding){
el.style.color = binding.value
})