測試生命周期鉤子函數代碼:
main.js
const v= new Vue({
data: {
hh:'數據',
arr: [1,2,3]
},
beforeCreate:function() {
console.log('beforeCreate******',this.hh,this.$el)
},
created:function() {
console.log('created:li的個數******',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的個數******',document.querySelectorAll('li').length)
console.log('beforeMount******',this.hh,this.$el)
},
mounted:function() {
console.log('mounted:li的個數******',document.querySelectorAll('li').length)
console.log('mounted******',this.hh,this.$el)
},
beforeUpdate:function() {
console.log('beforeUpdate:li的個數******',document.querySelectorAll('li').length)
console.log('beforeUpdate******',this.hh,this.$el)
},
updated:function() {
console.log('updated:li的個數******',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:
結果:
個人理解總結如下:
beforeCreated:創建前狀態。在實例初始化之后,數據觀測(data observer) 和 event/watcher 事件配置之前被調用。[此時數據,計算屬性,綁定方法,watcher 都讀不到]
created:實例創建完成狀態,可以調用實例的數據,方法。還未掛載,所以el是undefined。[此階段可以用來初始化緩存數據]
beforeMonted: 掛載鉤子,即將掛載,找掛載節點, 如果設定了el元素,那Vue實例一切操作只對這個根目錄和他的子元素生效。這個階段生成的是虛擬 Dom。
monted:掛載完成,dom渲染到了頁面中。此步可以用來操作獲取后臺數據。(實際項目中也曾在created狀態時用來異步獲取后臺數據,暫時不清楚最好是在哪一步進行此操作)
update:數據更新。數據更新和真正渲染到Dom中是有時間差的因為是事件隊列。[盡量避免在此階段更改狀態可能會導致無限循環。]
beforeDestroy:實例銷毀之前調用,在這一步,實例還是可用的。
destoryed:實例銷毀。解綁掉了所有數據,綁定方法,watcher,子實例等
以上測試代碼可從github上拉取測試:github拉取地址
之前看到一個描述比較詳細的文章,下圖是博主對生命周期的標注,清晰明了,對vue感興趣的朋友可以看看。鏈接是這個文章鏈接
昨天自己又畫了一遍流程如下:
不知道理解的對不對,如有問題請各位指教。