vue3生命中周期
Vue 3引入了Composition API,这是一个更灵活和易于组织代码的方式。因此,旧版本中的生命周期钩子函数在Vue 3中被重新设计和重命名了。我们可在源码文件packages\runtime-core\src\apiLifecycle.ts中看到所有的生命周期钩子
在Vue 3中,使用setup函数来初始化组件,并且不再使用像beforeCreate、created这样的钩子函数。相反,使用了一些新的函数来替代。
beforeCreate和created钩子函数已经被合并为一个新的函数,名为setup。在这个函数内部,您可以执行所有的初始化工作,并且可以访问到组件的props和context等。
beforeMount和mounted函数保持不变,它们依然在组件被挂载到DOM之前和之后调用,可以用于执行DOM操作或访问外部API等。
beforeUpdate和updated函数也保持不变,它们在组件的数据发生变化导致重新渲染之前和之后被调用。可以在这些函数中执行一些响应式数据的操作。
beforeUnmount函数是Vue 3中新引入的。它会在组件被卸载之前被调用,可以用于清除定时器、解绑事件等资源的释放。
此外,Vue 3还引入了onRenderTriggered和onRenderTracked函数,用于在组件渲染时跟踪和触发依赖项的变化。
生命周期具体变化如下:
Vue2-----------------------Vue3
beforeCreate -> setup()
created -> setup()
beforeMount -> onBeforeMount
mounted -> onMounted
beforeUpdate -> onBeforeUpdate
updated -> onUpdated
beforeDestroy -> onBeforeUnmount
destroyed -> onUnmounted
activated -> onActivated
deactivated -> onDeactivated
errorCaptured -> onErrorCaptured
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
注意,在vue3不能直接使用声明周期钩子,使用前需要先引入
import { onMounted } from 'vue'
onMounted(() => {
// do something
})
1
2
3
4
2
3
4
上次更新: 2025/09/05, 8:09:00