# 自定义指令

# 自定义指令的分类

vue 中的自定义指令分为两类:分别是 :

  • 私有自定义指令
  • 全局自定义指令

# 私有自定义指令

在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令

1
2
3
4
5
6
7
8
9
10
11
directives: {
//定义名为color的指令, 指向一个配置对象
color: {
//为绑定到的HTML元素设置红色的文字
//当指令第一次被绑定到元素上的时候, 会立即触发bind函数
bind(el) {
//形参中的el是绑定了此指令的原生的DOM对象
el.style.color = 'red'
}
}
}

# update 函数

bind 函数只调用一次:当指令第一次绑定到元素时调用,当 DOM 更新时 bind 函数不会被触发. update 函数会在每次 DOM 更新时被调用

1
2
3
4
5
6
7
directives: {
color: {
update(el, binding) {
el.style.backgroundColor = binding.value
}
}
}

# 函数简写形式

如果 bind 指令和 update 指令执行的内容一样,则可以将函数简写

1
2
3
4
5
directives: {
color(el, binding) {
el.style.backgroundColor = binding.value
}
}

# 全局自定义指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//main.js

Vue.directive('color', {
bind(el, binding) {
el.style.backgroundColor = binding.value
},
update(el, binding) {
el.style.backgroundColor = binding.value
}
})

//或者

Vue.directive('color', function(el, binding) {
el.style.backgroundColor = binding.value
})