# 自定义指令
# 自定义指令的分类
vue 中的自定义指令分为两类:分别是 :
# 私有自定义指令
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令
1 2 3 4 5 6 7 8 9 10 11
| directives: { color: { bind(el) { 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
|
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 })
|