測(cè)試生命周期鉤子函數(shù)代碼:
main.js
const v= new Vue({
data: {
hh:'數(shù)據(jù)',
arr: [1,2,3]
},
beforeCreate:function() {
console.log('beforeCreate******',this.hh,this.$el)
},
created:function() {
console.log('created:li的個(gè)數(shù)******',document.querySelectorAll('li').length)
console.log('created******',this.hh,this.$el)
setTimeout(() => {
this.arr= [6,7,8,9]
},0)
},
beforeMount:function() {
console.log('beforeMount:li的個(gè)數(shù)******',document.querySelectorAll('li').length)
console.log('beforeMount******',this.hh,this.$el)
},
mounted:function() {
console.log('mounted:li的個(gè)數(shù)******',document.querySelectorAll('li').length)
console.log('mounted******',this.hh,this.$el)
},
beforeUpdate:function() {
console.log('beforeUpdate:li的個(gè)數(shù)******',document.querySelectorAll('li').length)
console.log('beforeUpdate******',this.hh,this.$el)
},
updated:function() {
console.log('updated:li的個(gè)數(shù)******',document.querySelectorAll('li').length)
console.log('updated******',this.hh,this.$el)
},
beforeDestroy:function() {
console.log('beforeDestroy******',this.hh,this.$el)
},
destroyed:function() {
console.log('destroyed******',this.hh,this.$el)
}
}).$mount('#app')
// v.$destroy()
export default v
index.html:

結(jié)果:

個(gè)人理解總結(jié)如下:
beforeCreated:創(chuàng)建前狀態(tài)。在實(shí)例初始化之后,數(shù)據(jù)觀測(cè)(data observer) 和 event/watcher 事件配置之前被調(diào)用。[此時(shí)數(shù)據(jù),計(jì)算屬性,綁定方法,watcher 都讀不到]
created:實(shí)例創(chuàng)建完成狀態(tài),可以調(diào)用實(shí)例的數(shù)據(jù),方法。還未掛載,所以el是undefined。[此階段可以用來初始化緩存數(shù)據(jù)]
beforeMonted: 掛載鉤子,即將掛載,找掛載節(jié)點(diǎn), 如果設(shè)定了el元素,那Vue實(shí)例一切操作只對(duì)這個(gè)根目錄和他的子元素生效。這個(gè)階段生成的是虛擬 Dom。
monted:掛載完成,dom渲染到了頁(yè)面中。此步可以用來操作獲取后臺(tái)數(shù)據(jù)。(實(shí)際項(xiàng)目中也曾在created狀態(tài)時(shí)用來異步獲取后臺(tái)數(shù)據(jù),暫時(shí)不清楚最好是在哪一步進(jìn)行此操作)
update:數(shù)據(jù)更新。數(shù)據(jù)更新和真正渲染到Dom中是有時(shí)間差的因?yàn)槭鞘录?duì)列。[盡量避免在此階段更改狀態(tài)可能會(huì)導(dǎo)致無限循環(huán)。]
beforeDestroy:實(shí)例銷毀之前調(diào)用,在這一步,實(shí)例還是可用的。
destoryed:實(shí)例銷毀。解綁掉了所有數(shù)據(jù),綁定方法,watcher,子實(shí)例等
以上測(cè)試代碼可從github上拉取測(cè)試:github拉取地址
之前看到一個(gè)描述比較詳細(xì)的文章,下圖是博主對(duì)生命周期的標(biāo)注,清晰明了,對(duì)vue感興趣的朋友可以看看。鏈接是這個(gè)文章鏈接

昨天自己又畫了一遍流程如下:

不知道理解的對(duì)不對(duì),如有問題請(qǐng)各位指教。