Vue3系列 - 组件生命周期的执行顺序
Vue3中组件生命周期钩子的实现位于src/v3/apiLifecycle.ts,它定义了组件从创建到销毁的各个阶段。
生命周期钩子的执行顺序:
创建阶段:
onBeforeMount:组件挂载到DOM前调用onMounted:组件挂载到DOM后调用
更新阶段:
onBeforeUpdate:组件更新前调用onUpdated:组件更新后调用
销毁阶段:
onBeforeUnmount:组件卸载前调用onUnmounted:组件卸载后调用
特殊钩子:
onActivated:被keep-alive缓存的组件激活时调用onDeactivated:被keep-alive缓存的组件停用时调用onErrorCaptured:捕获后代组件错误时调用onRenderTracked:跟踪虚拟DOM重新渲染时调用onRenderTriggered:虚拟DOM重新渲染被触发时调用
生命周期钩子的实现机制:
function createLifeCycle<T extends (...args: any[]) => any = () => void>(
hookName: string
) {
return (fn: T, target: any = currentInstance) => {
if (!target) {
__DEV__ &&
warn(
`${formatName(hookName)} is called when there is no active component instance.`
)
return
}
return injectHook(target, hookName, fn)
}
}
function injectHook(instance: Component, hookName: string, fn: () => void) {
const options = instance.$options
options[hookName] = mergeLifecycleHook(options[hookName], fn)
}在父子组件嵌套的情况下,生命周期钩子的执行顺序是:
- 创建:父beforeCreate -> 父created -> 父beforeMount -> 子beforeCreate -> 子created -> 子beforeMount -> 子mounted -> 父mounted
- 更新:父beforeUpdate -> 子beforeUpdate -> 子updated -> 父updated
- 销毁:父beforeUnmount -> 子beforeUnmount -> 子unmounted -> 父unmounted
理解生命周期钩子的执行顺序对于正确管理组件状态和资源非常重要。