這是Vue文檔里關於實例生命周期的解釋圖
那么下面我們來進行測試一下
<section id="app-8"> {{data}} </section>
var myVue=new Vue({ el:"#app-8", data:{ data:"aaaaa", info:"nono" }, beforeCreate:function(){ console.log("創建前========") console.log(this.data) console.log(this.$el) }, created:function(){ console.log("已創建========") console.log(this.info) console.log(this.$el) }, beforeMount:function(){ console.log("mount之前========") console.log(this.info) console.log(this.$el) }, mounted:function(){ console.log("mounted========") console.log(this.info) console.log(this.$el) }, beforeUpdate:function(){ console.log("更新前========"); }, updated:function(){ console.log("更新完成========"); }, beforeDestroy:function(){ console.log("銷毀前========") console.log(this.info) console.log(this.$el) }, destroyed:function(){ console.log("已銷毀========") console.log(this.info) console.log(this.$el) } })
代碼如上,瀏覽器開始加載文件
由上圖可知:
1、beforeCreate 此時$el、data 的值都為undefined
2、創建之后,此時可以拿到data的值,但是$el依舊為undefined
3、mount之前,$el的值為“虛擬”的元素節點
4、mount之后,mounted之前,“虛擬”的dom節點被真實的dom節點替換,並將其插入到dom樹中,於是在觸發mounted時,可以獲取到$el為真實的dom元素()
myVue.$el===document.getElementById("app-8") // true
接着,在console中修改data,更新視圖
觸發beforeUpdata 和updated
接着,執行myVue.$destroy()
總結一下,對官方文檔的那張圖簡化一下,就得到了這張圖
文章中若有錯誤請指出,轉載請注明出處,謝謝~