Vue2 自定义指令

私有自定义指令

只能在定义自定义指令的组件中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<template>
<div>
<p v-color="color"></p>
</div>
</template>

<script>
export default {
data() {
return {
color: 'blue'
}
},
// 私有自定义指令
directives: {
color: {
// 指令第一次被绑定到元素上的时候执行
bind(el,binding) {
el.style.color = binding.value;
},
// 每次 DOM 更新的时候都会执行(第一次不会生效)
update(el,binding) {
el.style.color = binding.value;
},
},
},
};
</script>

bind 函数和 update 函数不冲突,并且互补

简写

当 bind 函数和 update 函数内容是相同的时候可以使用简写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<script>
export default {
data() {
return {
color: 'blue'
}
},
// 私有自定义指令简写
directives: {
color(el,binding) {
el.style.color = binding.value;
},
},
};
</script>

全局自定义指令

在所有的组件中都可以使用

1
2
3
Vue.directive('color', (el,binding) => {
el.style.color = binding.value;
})

第一个参数是自定义指令名称,第二个参数是自定义指令的行为

自定义指令需要绑定的元素在页面上插入时,才会执行