vue3和vue2生命周期的對比
Vue3 的生命周期比較多。
- setup() :開始創建組件之前,在beforeCreate和created之前執行。創建的是data和method
- onBeforeMount() : 組件掛載到節點上之前執行的函數。
- onMounted() : 組件掛載完成后執行的函數。
- onBeforeUpdate(): 組件更新之前執行的函數。
- onUpdated(): 組件更新完成之后執行的函數。
- onBeforeUnmount(): 組件卸載之前執行的函數。
- onUnmounted(): 組件卸載完成后執行的函數。
- onActivated(): 被包含在
中的組件,會多出兩個生命周期鈎子函數。被激活時執行。 - onDeactivated(): 比如從 A 組件,切換到 B 組件,A 組件消失時執行。
- onErrorCaptured(): 當捕獲一個來自子孫組件的異常時激活鈎子函數(以后用到再講,不好展現)。
注:使用<keep-alive> 組件會將數據保留在內存中,比如我們不想每次看到一個頁面都重新加載數據,就可以使用
vue3使用生命周期需要單獨從vue中引用,並且只能在setup函數內調用
Vue2--------------vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured