vue - 生命周期


 

Vue 實例有一個完整的生命周期,生命周期也就是指一個實例從開始創建到銷毀的這個過程。

 

  • beforeCreated():在實例創建之間執行,數據未加載狀態。

  • created():在實例創建、數據加載后,能初始化數據,DOM 渲染之前執行。

  • beforeMount():虛擬 DOM 已創建完成,在數據渲染前最后一次更改數據。

  • mounted():頁面、數據渲染完成,真實 DOM 掛載完成。

  • beforeUpadate():重新渲染之前觸發。

  • updated():數據已經更改完成,DOM 也重新 render 完成,更改數據會陷入死循環。

  • beforeDestory() 和 destoryed():前者是銷毀前執行(實例仍然完全可用),后者則是銷毀后執行。

 

如下圖:

 

 

代碼實踐

 

 // 生命周期可查看控制台打印 - 詳細信息
   beforeCreate: function() {
      console.group('------beforeCreate創建前狀態------'); console.log("%c%s", "color:red" , "el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //undefined console.log("%c%s", "color:red","message: " + this.message) }, created: function() { console.group('------created創建完畢狀態------'); console.log("%c%s", "color:red","el : " + this.$el); //undefined console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化  }, beforeMount: function() { console.group('------beforeMount掛載前狀態------'); console.log("%c%s", "color:red","el : " + (this.$el)); //已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化  }, mounted: function() { console.group('------mounted 掛載結束狀態------'); console.log("%c%s", "color:red","el : " + this.$el); //已被初始化 console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); //已被初始化 console.log("%c%s", "color:red","message: " + this.message); //已被初始化  }, beforeUpdate: function () { console.group('beforeUpdate 更新前狀態===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, updated: function () { console.group('updated 更新完成狀態===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, beforeDestroy: function () { console.group('beforeDestroy 銷毀前狀態===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message); }, destroyed: function () { console.group('destroyed 銷毀完成狀態===============》'); console.log("%c%s", "color:red","el : " + this.$el); console.log(this.$el); console.log("%c%s", "color:red","data : " + this.$data); console.log("%c%s", "color:red","message: " + this.message) }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM