跳至主要内容

[Vue] 生命週期

TL;DR

Vue本身是由元件所組成,包含最外層的#app也是一個元件。

本篇就是要介紹元件的一生(?

參考資料

相關連結


生命週期圖示

官方文件生命週期圖示

生命週期概述

vuejs
const child = {
template:`
<div>
<h4>{{ text }}</h4>
<input type="text" class="form-control" v-model="text">
</div>
`,
data: function () {
return {
text: 'Vue data 資料狀態'
}
},
beforeCreate() {
console.log(`beforeCreate! ${this.text}`);
},
created() {
console.log(`created! ${this.text}`);
alert(`created! ${this.text}`);
},
beforeMount() {
alert(`beforeMount! ${this.text}`);
},
mounted() {
alert(`mounted! ${this.text}`);
},
updated () {
console.log(`updated! ${this.text}`);
},
activated () {
alert(`activated! ${this.text}`);
},
deactivated () {
alert(`deactivated! ${this.text}`);
},
beforeUnmount() {
console.log(`beforeUnmount! ${this.text}`);
},
unmounted() {
console.log(`unmounted! ${this.text}`);
}
};
const App = {
data() {
return {
isShowing: false
}
}
};
Vue.createApp(App).component('child',child).mount('#app');

v-if & v-show

使用v-if時,元件會經歷完整的生命週期。

所以上述範例在v-if是false的時候,元件是卸載的狀態。

直到v-if為true時,會經歷beforeCreate,created,beforeMount,mounted

接著當v-if再次轉變為false時,會經歷beforeUnmount,最後為unmounted。此時元件完全移除。

但是v-show則會一開始就執行完整的:beforeCreate,created,beforeMount,mounted

直接將元件給掛載上去。接著調整display:none,來隱藏元件。

元件狀態保留

activated () {
alert(`activated! ${this.text}`);
},
deactivated () {
alert(`deactivated! ${this.text}`);
}

可以發現上述範例這兩個method並沒有被觸發。這是因為這兩個API只有在保留元件狀態時會使用到。

TBD

待補完整