一、自定義指令的生命周期
自定義指令有五個生命周期(也叫鈎子函數),分別是 bind,inserted,update,componentUpdated,unbind
- bind:只調用一次,指令第一次綁定到元素時調用,用這個鈎子函數可以定義一個綁定時執行一次的初始化動作。
- inserted:被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於document中)。
- update:被綁定於元素所在的模板更新時調用,而無論綁定值是否變化。通過比較更新前后的綁定值,可以忽略不必要的模板更新。
- componentUpdated:被綁定元素所在模板完成一次更新周期時調用。
- unbind:只調用一次,指令與元素解綁時調用。
二、VUE生命周期
Vue一共有10個生命周期函數,官網有張圖幫助理解:
如下代碼(應該看代碼就能看懂):
add:function(){
this.num++;
},
beforeCreate:function(){
console.log('1-beforeCreate 初始化之前');
},
created:function(){
console.log('2-created 創建完成');
},
beforeMount:function(){
console.log('3-beforeMount 掛載之前');
},
mounted:function(){
console.log('4-mounted 被掛載');
},
beforeUpdate:function(){
console.log('5-beforeUpdate 數據更新前');
},
updated:function(){
console.log('6-updated 被更新后');
},
activated:function(){
console.log('7-activated');
},
deactivated:function(){
console.log('8-deactivated');
},
beforeDestroy:function(){
console.log('9-beforeDestroy 銷毀之前');
},
destroyed:function(){
console.log('10-destroyed 銷毀之后')
}