Vue生命周期是面試中經(jīng)常被問到的問題,在實(shí)際項(xiàng)目中很多坑都是關(guān)于生命周期的,所以理解Vue實(shí)例的生命周期很有必要。筆者參考了一些文章,對(duì)Vue實(shí)例的生命周期做了總結(jié),既是總結(jié)筆記以便以后參考,也是供大家一起學(xué)習(xí)交流。
以下這張圖是Vue官網(wǎng)上的,我會(huì)利用鉤子函數(shù)一步一步講解Vue實(shí)例生命周期中發(fā)生了什么。

beforeCreate

編寫以下代碼:
<--index.html-->
<div id="app">
{{msg}}
</div>
var app = new Vue({
el:'#app',
data: {
msg: 'hello world!'
},
beforeCreate(){
console.log('beforeCreate:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
}
})
運(yùn)行代碼,在后臺(tái)得到以下輸出:

由此可以得到,鉤子函數(shù)beforeCreate()運(yùn)行時(shí),Vue實(shí)例還在初始化過程中,但是el選項(xiàng)和data數(shù)據(jù)并沒有被初始化。所以此時(shí)無法獲得data數(shù)據(jù),如果偏要在此時(shí)獲取data的之呢?可參考這個(gè)回答。
created

同樣的html代碼,更換鉤子函數(shù):
var app = new Vue({
el:'#app',
data: {
msg: 'hello world!'
},
created(){
console.log('created:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
}
})
運(yùn)行代碼,得到一下結(jié)果:
所以,當(dāng)created()函數(shù)運(yùn)行時(shí)el選項(xiàng)并沒有被初始化,data數(shù)據(jù)被初始化了,可以通過created()獲得data對(duì)象里的值。
beforeMount

html代碼不變,更換鉤子函數(shù):
var app = new Vue({
el:'#app',
data: {
msg: 'hello world!'
},
beforeMount(){
console.log('beforeMount:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
}
})
在后臺(tái)得到以下輸出結(jié)果:
所以,beforeMount鉤子函數(shù)被調(diào)用時(shí),el和data都被初始化了,但是此時(shí)el還是虛擬Dom節(jié)點(diǎn)。
mounted

更改代碼:
var app = new Vue({
el:'#app',
data: {
msg: 'hello world!'
},
mounted(){
console.log('mounted:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
}
})
運(yùn)行代碼,得到一下結(jié)果:
所以,mounted鉤子函數(shù)運(yùn)行時(shí),值已經(jīng)被渲染在了頁面上。
beforeUpdate和Updated

修改代碼:
var app = new Vue({
el:'#app',
data: {
msg: 'hello world!'
},
beforeUpdate(){
console.log('beforeUpdate:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
},
updated(){
console.log('updated:');
console.log('el:', this.$el);
console.log('msg:', this.msg);
}
})
在控制臺(tái)修改msg的值,得到以下結(jié)果:
發(fā)現(xiàn)兩個(gè)鉤子函數(shù)沒有任何區(qū)別,其實(shí)beforeUpdate函數(shù)被調(diào)用時(shí),data里msg的值已經(jīng)改變了,但是沒有渲染到頁面上,所以那時(shí)的頁面顯示的還是舊值,頁面渲染完畢之后才會(huì)調(diào)用Updated,這就是兩個(gè)鉤子函數(shù)調(diào)用時(shí)的區(qū)別。
beforeDestroy和destroyed
beforeDestroy鉤子函數(shù)在實(shí)例銷毀之前調(diào)用。在這一步,實(shí)例仍然完全可用。
destroyed鉤子函數(shù)在Vue 實(shí)例銷毀后調(diào)用。調(diào)用后,Vue 實(shí)例指示的所有東西都會(huì)解綁定,所有的事件監(jiān)聽器會(huì)被移除,所有的子實(shí)例也會(huì)被銷毀。
參考文章:
https://cn.vuejs.org/v2/guide/instance.html#%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E5%9B%BE%E7%A4%BA
https://segmentfault.com/a/1190000008010666?utm_source=tag-newest
https://segmentfault.com/a/1190000011381906?utm_source=tag-newest