关键API介绍
Vue.directive( id, [definition])
- 参数:
{string} id
{Function | Object} [definition]
// 注册
Vue.directive('myDirective', {
bind: function () {},
inserted: function () {},
update: function () {},
componentUpdated: function () {},
unbind: function () {}
})
// 注册 (指令函数)
Vue.directive('myDirective', function () {
// 这里将会被 `bind` 和 `update` 调用
})
// getter,返回已注册的指令
var myDirective = Vue.directive('myDirective')
钩子函数解释
bind
:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。
inserted
:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。
update
:所在组件的 VNode 更新时调用,但是可能发生在其子 VNode 更新之前。指令的值可能发生了改变,也可能没有。
componentUpdated
:指令所在组件的 VNode 及其子 VNode 全部更新后调用。
unbind
:只调用一次,指令与元素解绑时调用。
钩子函数参数
指令钩子函数都会三个参数:el、binding、vnode、oldVnode(仅update、componentUpdated)
el
:指令所绑定的元素,可以用来直接操作 DOM。binding
:一个对象,包含以下 property:name
:指令名,不包括 v- 前缀。value
:指令的绑定值,例如:v-myDirective="2"
中,绑定值为2
。oldValue
:指令绑定的前一个值,仅在update
和componentUpdated
钩子中可用。无论值是否改变都可用。expression
:字符串形式的指令表达式。例如v-myDirective="1 + 1"
中,表达式为"1 + 1"
。arg
:传给指令的参数,可选。例如v-myDirective:foo
中,参数为"foo"
。modifiers
:一个包含修饰符的对象。例如:v-myDirective.foo.bar
中,修饰符对象为{ foo: true, bar: true }
。
vnode
:Vue 编译生成的虚拟节点。oldVnode
:上一个虚拟节点,仅在update
和componentUpdated
钩子中可用
函数简写
当bind
和 update
时触发相同行为,而不关心其它的钩子的时候。可以这样写:
Vue.directive('myDirective',function(el,binding){
console.log(el,binding.value)
})
对象字面量
如果指令需要多个值,可以传入一个 JavaScript 对象字面量,指令函数能够接受所有合法的 JavaScript 表达式。
<div v-demo="{ color: 'white', text: 'hello' }"></div>
Vue.directive('demo', function (el, binding) {
console.log(binding.value.color) // "white"
console.log(binding.value.text) // "hello"
})
自定义防抖指令案例
给button按钮添加自定义防抖指令
<template>
<button type="primary" v-debounce="saveMessage" >确 定</button>
</template>
<script>
export default {
methods:{
saveMessage() {
console.log('被点击了!')
},
}
}
</script>
// main.js
import Vue from 'vue'
Vue.directive('debounce', {
bind: function (el, binding) {
el.addEventListener('click', () => {
if (!el.disabled) {
binding.value(); // value 相当于saveMessage;
el.disabled = true
setTimeout(() => {
el.disabled = false
}, 1500) // 定时器 1.5秒之后才能点击
}
});
}
});
// 可以尝试去简写
点赞 评论 收藏 ~~ 留言讨论,如有错误,也希望大家不吝指出。 ~~ 点赞 评论 收藏