2023/01/02

Vue.js 生命週期 Life Cycle

 


Vue主要有以下八個週期
生命週期 描述
beforeCreate 創建Vue實例前
created 創建Vue實例後
beforeMount 掛載DOM之前
mounted 掛載DOM後
beforeUpdate 更新數據前
updated 更新數據後
beforeDestroy 銷毀Vue實例前
destroyed 銷毀Vue實例後

特殊週期則有三個
特殊生命週期 描述
activated keep-alive緩存組件激活時
deactivated keep-alive緩存組件停用時
errorCaptured 捕捉到來自一個子孫組件錯誤時

Keep-Alive代碼如下:
<keep-alive>
    <component/>
</keep-alive>

Keep-Alive有三個props:
  • include:需要緩存的組件
  • exclude:不需要緩存的組件
  • max:緩存數量上限
Keep-Alive較為常用在以下情境:
  • 元件重新渲染時都會呼叫API取得資料
  • 需要切換內容

不過被Keep-Alive包覆的組件在切換時,僅會觸發activated和deactivated的生命週期而不會觸發mounted和unmounted,子孫組件也適用activated和deactivated

不過上述生命週期再3.x版本有開始提供Composition API,其差異如下:
Vue 2.x / 3.x Vue 3.x Composition API 描述
beforeCreate setup() 創建Vue實例前
created setup() 創建Vue實例後
beforeMount onBeforeMonut 掛載DOM之前
mounted onMounted 掛載DOM後
beforeUpdate onBeforeUpdate 更新數據前
updated onUpdated 更新數據後
beforeDestroy 2.x onBeforeUnmount 銷毀Vue實例前
beforeUnmount 3.x onBeforeUnmount 銷毀Vue實例前
destroyed 2.x onUnmounted 銷毀Vue實例後
unmounted 3.x onUnmounted 銷毀Vue實例後
activated keep-alive緩存組件激活時
deactivated keep-alive緩存組件停用時
errorCaptured 捕捉到來自一個子孫組件錯誤時

Composition API是再Vue3.x版本被實作出來的,再講解Composition API前我們需要先回顧下Vue 2.x。
再Vue 2.x時是透過Options API去撰寫的,再組件內會data擺放資料,再methods寫功能邏輯;在我們維護時通常要去找到data以及對應的方法才有辦法維護,如果專案非常龐大時再維護時也會顯得困難。
Composition API則可以將data和methods寫再一起,更可以根據邏輯來分割程式碼

created與mounted區別:
created再建立時,DOM尚未生成;mounted則是DOM節點渲染完後會觸發的;兩者相同的點再於都能拿到實例對象的屬性和方法

參考資料:
https://vue3js.cn/interview/vue/lifecycle.html#%E4%B8%89%E3%80%81%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E6%95%B4%E4%BD%93%E6%B5%81%E7%A8%8B

https://peterhpchen.github.io/VuejsQuest/basic/04_Lifecycle.html

https://bbs.huaweicloud.com/blogs/278913

https://segmentfault.com/a/1190000014640577

https://juejin.cn/post/6844903602356502542

https://medium.com/%E5%B0%8F%E5%BD%A5%E5%BD%A5%E7%9A%84%E5%89%8D%E7%AB%AF%E4%BA%94%E5%9B%9B%E4%B8%89/vue-js-vue%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F-fc971fac8298

https://cn.vuejs.org/api/built-in-components.html#keepalive

https://cn.vuejs.org/guide/built-ins/keep-alive.html#lifecycle-of-cached-instance

https://ithelp.ithome.com.tw/articles/10279321