目錄
前言
在 Vue3 中的生命周期函數,與 Vue2 中略有不同
生命周期函數的用法
Vue3 中,要在 setup()
函數中使用生命周期來完成需求
當你需要使用生命周期時,直接導入 onxxx
一族的生命周期鉤子:
import { onMounted, onUpdated, onUnmounted } from 'vue'
const MyComponent = {
setup() {
onMounted(() => {
console.log('mounted!')
})
onUpdated(() => {
console.log('updated!')
})
onUnmounted(() => {
console.log('unmounted!')
})
},
}
這些生命周期鉤子只能在 setup()
內部同步使用,因為他們依賴正在調用 setup()
的組件實例。
看到這里,想必你的感觸一定很深了——你會發現 Vue3 與 react17 的發展方向開始相似,所以說,好好學 JS 吧~
與 2.x 版本相對應的生命周期鉤子
Vue2.x 的生命周期 | Vue3.x 的生命周期 |
---|---|
使用 setup() | |
使用 setup() | |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroy | onBeforeUnmount |
destroyed | onUnmounted |
errorCaptured | onErrorCaptured |
新增的鉤子函數
除了與 Vue2.x 等效的生命周期之外,composition-api
還新增了以下生命周期鉤子用作調試:
- onRenderTracked
- onRenderTriggered
兩個鉤子函數都接收一個 DebuggerEvent
:
export default {
onRenderTriggered(e) {
debugger
// 檢查哪個依賴性導致組件重新渲染
},
}