[Medium] 📄 Vue Lifecycle Hooks
1. Please explain Vue lifecycle hooks (include Vue 2 & Vue 3)
請解釋 Vue 的生命週期鉤子(包含 Vue 2 和 Vue 3)
Vue 組件從創建到銷毀會經歷一系列的過程,在這些過程中會自動呼叫特定的函式,這些函式就是「生命週期鉤子」。理解生命週期對於掌握組件的行為非常重要。
Vue 生命週期圖解
建立階段 → 掛載階段 → 更新階段 → 銷毀階段
↓ ↓ ↓ ↓
Created Mounted Updated Unmounted
Vue 2 vs Vue 3 生命週期對照表
| Vue 2 (Options API) | Vue 3 (Options API) | Vue 3 (Composition API) | 說明 |
|---|---|---|---|
beforeCreate | beforeCreate | setup() | 組件實例初始化之前 |
created | created | setup() | 組件實例創建完成 |
beforeMount | beforeMount | onBeforeMount | 掛載到 DOM 之前 |
mounted | mounted | onMounted | 掛載到 DOM 之後 |
beforeUpdate | beforeUpdate | onBeforeUpdate | 資料更新前 |
updated | updated | onUpdated | 資料更新後 |
beforeDestroy | beforeUnmount | onBeforeUnmount | 組件卸載之前 |
destroyed | unmounted | onUnmounted | 組件卸載之後 |
activated | activated | onActivated | keep-alive 組件激活時 |
deactivated | deactivated | onDeactivated | keep-alive 組件停用時 |
errorCaptured | errorCaptured | onErrorCaptured | 捕獲子組件錯誤時 |
1. 建立階段(Creation Phase)
beforeCreate / created
<script>
export default {
data() {
return {
message: 'Hello Vue',
};
},
beforeCreate() {
// ❌ 此時 data、methods 都還未初始化
console.log('beforeCreate');
console.log(this.message); // undefined
console.log(this.$el); // undefined
},
created() {
// ✅ 此時 data、computed、methods、watch 都已初始化
console.log('created');
console.log(this.message); // 'Hello Vue'
console.log(this.$el); // undefined(尚未掛載到 DOM)
// ✅ 適合在這裡發送 API 請求
this.fetchData();
},
methods: {
async fetchData() {
const response = await fetch('/api/data');
this.data = await response.json();
},
},
};
</script>
使用時機:
beforeCreate:很少使用,通常用於插件開發created:- ✅ 發送 API 請求
- ✅ 初始化非響應式的資料
- ✅ 設定事件監聽器
- ❌ 無法操作 DOM(尚未掛載)