vue---生命週期
vue例項有一個完整的生命週期,也就是vue例項從 建立前(beforeCreate)、建立後(created)、載入前(beforeMount)、載入後(mounted)、更新前(beforeUptate)、更新後(updated)、銷燬前(beforeDestroy)、銷燬後(destroyed)一系列過程,我們稱之為vue的生命週期。
通俗來講就是vue例項從建立到銷燬的過程就是生命週期。
我們一般把vue的生命週期分為三個階段:初始化、執行中、銷燬。
(1) beforeCreate:
beforeCreate() { console.log('beforeCreate--$el:', this.$el); console.log('beforeCreate--$data:', this.$data); console.log('beforeCreate--res:', this.res); }
從列印的結果來看我們知道:
beforeCreate --- 在vue例項完全被創建出來之前(意思就是說vue例項還沒有被完全創建出來)被呼叫,此時資料還沒有被初始化,所以無法訪問資料,
(2) created:
created() { console.log('created--$el:', this.$el); console.log('created--$data:', this.$data); console.log('created--res:', this.res); }
從列印的結果來看我們知道:
created --- 在vue例項建立完成後被呼叫,這個過程已完成了資料的初始化,可以被訪問得到;這個過程可以修改資料,這也是渲染之前修改資料的機會。
(3) beforeMount:
beforeMount() { console.log('beforeMount--$el:', this.$el); console.log('beforeMount--$data:', this.$data); console.log('beforeMount--res:', this.res); },
beforeMount --- 這個過程是在模版掛載之前被呼叫,render函式也是首次被呼叫,此時完成了虛擬Dom的構建,但並未被渲染,這也是最後一次修改資料的機會。
(4) mounted:
mounted() { console.log('mounted--$el:', this.$el); console.log('mounted--$data:', this.$data); console.log('mounted--res:', this.res); },
mounted --- 這個過程在模版掛載之後被呼叫,完成渲染,所以我們可以操作Dom。
(5) beforeUpdate:
這個鉤子函式是在重新渲染之前(更新前)呼叫,這個過程是不能更改資料的;如果在呼叫這個鉤子函式之前資料沒有改變的話,是無任何變化的;當資料發生改變之後,這個過程再次呼叫render函式,它會重新構建虛擬Dom,然後與上次生成的虛擬Dom樹利用diff演算法進行對比找出差異,準備下次的重新渲染。
(6) updated:
這個過程在重新渲染之後(更新後呼叫),已渲染完成
(7) beforeDestroy:
這個過程是vue例項銷燬之前被呼叫,在這個過程中我們可以做一些事情,比如 清除計時器或事件等等。
(8) destroyed:
vue例項銷燬後呼叫,並且vue例項中所有的東西都會解綁,所有的事件監聽器都會被移除,所有的子例項也會被銷燬。