參考網(wǎng)址: https://www.cnblogs.com/Syinho/p/12482012.html
什么是生命周期函數(shù)
在vue實(shí)例化過程中的某個(gè)時(shí)間點(diǎn)會(huì)自動(dòng)觸發(fā)的函數(shù)
生命周期的三個(gè)階段及相關(guān)的鉤子
創(chuàng)建階段
beforeCreate
created
beforeMount
mounted
運(yùn)行階段
- beforeUpdate
- updated
銷毀階段
- beforeDestroy
- destroyed
每個(gè)生命周期函數(shù)的特點(diǎn)
beforeCreate
創(chuàng)建之前,在beforeCreate生命周期執(zhí)行的時(shí)候,data和methods中的數(shù)據(jù)都還沒有初始化,不能訪問data數(shù)據(jù)
beforeCreate(){
console.log('beforeCreate',this.msg);
},
created
創(chuàng)建之后,data和methods中的數(shù)據(jù)已經(jīng)初始化柱宦,此時(shí)可以訪問data數(shù)據(jù)
一般在這個(gè)函數(shù)中發(fā)起ajax請(qǐng)求
created(){
console.log('created',this.msg);
},
beforeMount
掛載之前,表示模板已經(jīng)在內(nèi)存中編譯完成,但尚未把模板渲染到頁(yè)面中析恋。
此時(shí)還沒有渲染用數(shù)據(jù)生成的新dom
beforeMount(){
console.log('beforeMount',this.$el);
},
mounted
表示內(nèi)存中的模板,已經(jīng)真實(shí)的掛載到了頁(yè)面中盛卡,用戶已經(jīng)可以看到渲染好的頁(yè)面了
此時(shí)可以訪問dom
mounted(){
console.log('mounted',this.$el);
},
beforeUpdate
當(dāng)且僅當(dāng)data被修改時(shí)才觸發(fā)這個(gè)生命周期函數(shù)助隧,但此時(shí)僅僅是數(shù)據(jù)被修改,頁(yè)面還未更新滑沧。
如果修改的data數(shù)據(jù)并沒有在模板中使用并村,也不會(huì)觸發(fā)更新
beforeUpdate(){
console.log('beforeUpdate',this.msg);
console.log('beforeUpdate',this.$el.innerHTML);
},
updated
會(huì)根據(jù)新數(shù)據(jù)生成最新的內(nèi)存DOM樹,重新渲染到真實(shí)的頁(yè)面中去滓技,此時(shí)的data數(shù)據(jù)和頁(yè)面已完成同步
updated(){
console.log('updated',this.$el.innerHTML);
},
beforeDestroy
當(dāng)執(zhí)行beforeDestory鉤子函數(shù)的時(shí)候哩牍,Vue實(shí)例就已經(jīng)從運(yùn)行階段,進(jìn)入到了銷毀階段令漂。
當(dāng)執(zhí)行beforeDestory的時(shí)候膝昆,實(shí)例身上所有的data和所有的methods,以及過濾器叠必、指令...都處于可用狀態(tài)荚孵,此時(shí)還沒有真正執(zhí)行銷毀過程。
beforeDestroy(){
console.log('beforeDestroy');
},
destroyed
當(dāng)執(zhí)行到destoryed函數(shù)的時(shí)候纬朝,組件已經(jīng)被全部銷毀了收叶,data與methods均不可用。
更改data數(shù)據(jù)共苛,頁(yè)面不會(huì)更新
destroyed(){
console.log('destroyed');
}