关于Vue自定义钩子函数
Vue自定义钩子函数
- bind
- inserted
- update
- componentUpdated
- unbind
一个简单案例
<div id="app">
<my-comp v-if="msg" :msg="msg"></my-comp>
<button @click="update">更新</button>
<button @click="uninstall">卸载</button>
<button @click="install">安装</button>
</div>
Vue.directive('hello', {
bind: function (el){
console.log('bind');
},
inserted: function (el){
console.log('inserted');
},
update: function (el){
console.log('update');
},
componentUpdated: function (el){
console.log('componentUpdated');
},
unbind: function (el){
console.log('unbind');
}
});
var myComp = {
template: '<h1 v-hello>{{msg}}</h1>',
props: {
msg: String
}
}
new Vue({
el: '#app',
data: {
msg: 'Hello'
},
components: {
myComp: myComp
},
methods: {
update: function (){
this.msg = 'Hi';
},
uninstall: function (){
this.msg = '';
},
install: function (){
this.msg = 'Hello';
}
}
})
页面加载
执行bind 和 inserted
但是要注意的是 出现bind时父节点是为null
出现inserted时父节点是存在的 不为null
点击更新按钮数据更改
执行update和 componentUpdated
但是要注意的是
update是数据更新前
componentUpdated是数据更新后
页面卸载