Vue生命周期詳解
1、定義
生命周期函數(shù)(俗稱:鉤子函數(shù))
根據(jù)vue整個渲染機制,在渲染的每個關(guān)鍵點上,提供對應(yīng)的函數(shù),進行一些相關(guān)的業(yè)務(wù)操作。
2、四個階段
初始階段:beforeCreate():可以加loading效果、
created():結(jié)束loading效果,發(fā)請求,獲取數(shù)據(jù),添加定時器;

①創(chuàng)建Vue實例、②初始化事件對象和生命周期、③調(diào)用beforeCreate()鉤子函數(shù)(無法訪問data)
④初始化數(shù)據(jù)代理和數(shù)據(jù)監(jiān)測、⑤調(diào)用created()鉤子函數(shù)(可以訪問打他對象屬性)
⑥編譯模板語句生成虛擬DOM
掛載階段:beforeMount()、mounted();

①調(diào)用beforeMount()鉤子函數(shù),(真實DOM未生成),②給vm追加$el屬性,用它來代替"$el","¥el"代表了真是的DOM元素(真實DOM生成,頁面渲染完成)③調(diào)用mounted()鉤子函數(shù)(可以操作DOM元素)。
更新階段:beforeUpdate()、updated();

①data發(fā)生變化,②調(diào)用beforeUpdate()鉤子函數(shù)(數(shù)組發(fā)生變化,頁面未更新)(手動移除事件監(jiān)聽器)、③虛擬DOM重新渲染和修補、④調(diào)用updated鉤子函數(shù)(頁面已更新)(可以對數(shù)據(jù)做統(tǒng)一處理)
銷毀階段:beforeDestroy()、destroyed()。

①調(diào)用 this.$destroy()方法、②調(diào)用beforeDestroy()鉤子函數(shù)(做銷毀前的準備工作)、③卸載子組件和監(jiān)聽器、解綁自定義事件監(jiān)聽器、④調(diào)用destroyed()鉤子函數(shù)(所有的東西已經(jīng)解綁)
<div class="vues">
<h1>{{msg}}</h1>
<h1>{{count}}</h1>
<button @click="add">點我加1</button>
<button @click="destroy">點擊銷毀</button>
</div>
<script>
new Vue({
el: ".vues",
data: {
msg: '生命周期',
count: 0
},
methods: {
add: function () {
this.count++
},
destroy() {
this.$destroy()
}
},
/*
1、初始階段
el有,template也有,最終編譯template模板語句
el有,template沒有,最終編譯el模板語句
el沒有的時候,需要手動調(diào)用vm.$mount(el) 進行手動掛載,然后流程才能繼續(xù),
此時如果template有,最終編譯template模板語句
el沒有的時候,需要手動調(diào)用vm.$mount(el) 進行手動掛載,然后流程才能繼續(xù),v
此時如果template沒有,最終編譯el模板語句
結(jié)論:流程想要控制:el必須存在
el和template同時存在,優(yōu)先選擇template,如果沒有template才選擇el
*/
beforeCreate() {
// 創(chuàng)建前:數(shù)據(jù)代理和數(shù)據(jù)監(jiān)測的創(chuàng)建前
// 此時還無法訪問data當(dāng)中的數(shù)據(jù),包括methods也是無法訪問的。
console.log("beforeCreate");
},
created() {
// 創(chuàng)建后:表示數(shù)據(jù)代理和數(shù)據(jù)監(jiān)測創(chuàng)建完畢,可以訪問data中的數(shù)據(jù)了。
// 可以訪問methods
console.log('created');
},
beforeMount() {
console.log('beforeMount');
},
mounted() {
console.log('mounted');
},
beforeUpdate() {
console.log("beforeUpdate");
},
updated() {
console.log('updated');
},
beforeDestroy() {
console.log('beforeDestroy');
},
destroyed() {
console.log('destroyed');
}
})
</script>到此這篇關(guān)于Vue生命周期詳解的文章就介紹到這了,更多相關(guān)Vue生命周期內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
動態(tài)實現(xiàn)element ui的el-table某列數(shù)據(jù)不同樣式的示例
這篇文章主要介紹了動態(tài)實現(xiàn)element ui的el-table某列數(shù)據(jù)不同樣式的示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
Vue唯一可以更改vuex實例中state數(shù)據(jù)狀態(tài)的屬性對象Mutation的講解
今天小編就為大家分享一篇關(guān)于Vue唯一可以更改vuex實例中state數(shù)據(jù)狀態(tài)的屬性對象,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-01-01
Vue引入路徑正確但一直報錯問題:Already included file name&n
這篇文章主要介紹了Vue引入路徑正確但一直報錯:Already included file name ‘××ב differs from file name ‘××ב only in casing.具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12

