Vue指令上篇文章有讲过了,现在分析Vue指令钩子函数。
自定义指令
全局定义:Vue.directive( ' 自定义指令名 ' , { } );
参数一是指令的名字,定义时指令前不需要加 v- 前缀,但调用的时候必须加上这个前缀;
参数二是一个对象,在这对象身上有一些指令相关的函数,这些函数可以在特定阶段执行相关的操作,叫钩子函数。
钩子函数
//注册一个全局自定义指令
Vue.directive('demo', {
// 指令第一次绑定到元素时,会立即执行这个bind函数,只执行一次
bind: function () {
console.log('bind');
},
// inserted表示元素插入到DOM中时,会执行inserted函数,只触发一次。
inserted: function (el) {
console.log('inserted');
},
// 被绑定元素所在的模板更新时调用,而不论绑定值是否变化。
update:function(){
console.log('updated');
},
// 被绑定元素所在模板完成一次更新周期时调用。
componentUpdated: function () {
console.log('componentUpdated');
},
// 只调用一次,指令与元素解绑时调用
unbind: function () {
console.log('unbind')
}
})
所以钩子函数的作用:
-
bind
:只调用一次,指令第一次绑定到元素时调用,用这个钩子函数可以定义一个在绑定时执行一次的初始化动作。 -
inserted
:inserted表示元素插入到DOM中时,会执行inserted函数,只触发一次。 -
update
:被绑定元素所在的模板更新时调用,而不论绑定值是否变化。 -
componentUpdated
:被绑定元素所在模板完成一次更新周期时调用。 -
unbind
:只调用一次,指令与元素解绑时调用。
执行顺序
代码:
<template>
<div class="content">
<input type="text" v-model="msg" v-demo>
</div>
</template>
<script>
import Vue from 'vue'
Vue.directive('demo', {
bind: function () {
console.log('bind')
},
inserted: function (el) {
console.log('inserted')
},
update: function () {
console.log('updated')
},
componentUpdated: function () {
console.log('componentUpdated')
},
unbind: function () {
console.log('unbind')
}
})
export default {
data () {
return {
msg: 'hello'
}
}
}
</script>
执行效果图:
由此可知,bind比inserted先执行,当触发输入框,改变数据时,看其执行结果:
所以执行顺序是:bind ==> inserted ==> updated ==> componentUpdated
嘿嘿,unbind我也不清楚怎么描述。
参数
钩子函数中是可以带参数的。所带的参数也是有规定的,所以来分析参数。
-
el
:所绑定的元素,可直接操作dom
-
binding
:可获取使用了此指令的绑定值有多个属性-
name
:指令名,不包括v-前缀 -
value
:指令的绑定值,如v-demo="1+1"中,绑定值为2 -
oldValue
:指令绑定的前一个值,仅在update和componentUpdated中可用 -
expression
:字符串形式的指令表达式,例如v-demo = "1 + 1"中,表达式为"1 + 1" -
argument
:传给指令的参数,可选。例如v-demo:message中,参数为"message" -
modifiers
:一个包含修饰符的对象。例如v-demo.foo.bar中,修饰符对象为{foo:true, bar:true}
-
-
vnode
: 编译生成的虚拟节点 -
oldVnode
:上一个虚拟节点,仅在 update 和 componentUpdated 钩子中可用。
例子
拿钩子函数bind做例子:
<template>
<div class="content">
<input type="text" v-model="msg" v-demo.foo.bar="msg">
</div>
</template>
<script>
import Vue from 'vue'
Vue.directive('demo', {
bind: function (el, binding, vnode) {
console.log(el)
console.log(binding)
console.log(vnode)
}
})
export default {
name: 'Mixin',
data () {
return {
msg: 'hello'
}
}
}
</script>
效果图: