Vue 3 生命週期
2025年7月2日
學會對應 Composition API 的生命週期,有助於更穩定與清晰的元件開發。
生命週期 Hook 對應表
| 階段 | Options API | Composition API |
|---|---|---|
| 掛載前 | beforeMount | onBeforeMount |
| 掛載後 | mounted | onMounted |
| 更新前 | beforeUpdate | onBeforeUpdate |
| 更新後 | updated | onUpdated |
| 卸載前 | beforeUnmount | onBeforeUnmount |
| 卸載後 | unmounted | onUnmounted |
常見問題與觀念
- onMounted 和 created 差異? created 執行時 DOM 尚未存在,onMounted 執行時才可操作 DOM
- onUnmounted 有什麼用途? 常用於清理計時器、取消監聽或終止 API 請求
- setup() 什麼時候執行? 在 beforeCreate / created 之間,且是 Composition API 的進入點
- 何時使用 onUpdated? 當你要在 DOM 渲染完後取值、重新計算、或處理畫面更新
- onActivated / onDeactivated 有什麼用途? 搭配 <keep-alive> 使用,處理頁籤切換等情境
watch vs watchEffect 差異
兩者皆用於追蹤變數變化,但用途不同:
watch:需指定追蹤目標,支援新舊值watchEffect:立即執行,會自動追蹤依賴變數
ref vs reactive 差異
用於聲明響應式資料的兩種方式:
ref:適用於基本型別,透過.value存取reactive:適用於物件型別,可直接操作屬性
v-model 雙向綁定原理
Vue 3 中的 v-model 實際上會對應 :modelValue 與 @update:modelValue。
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
v-model 修飾符(Modifiers)
Vue 提供三個實用修飾符來處理輸入值格式:
| 修飾符 | 功能 | 使用情境 |
|---|---|---|
.trim | 自動去除空白字元 | 輸入名稱、帳號避免空格 |
.number | 將輸入字串轉為數字 | 數字欄位如年齡、金額 |
.lazy | 延遲更新至 change 事件 | 避免即時更新,提高效能 |
範例:
<input v-model.trim="name" />
<input v-model.number="age" />
<input v-model.lazy="email" />
補充:錯誤處理與狀態追蹤
onErrorCaptured:類似 try/catch 的作用,用來集中錯誤處理watchEffect:在 setup 中立即執行,用於追蹤 reactive 狀態
想知道 Pinia 跟 Vuex 的區別嗎?參考: Vuex 與 Pinia
