在 Vue 3 的 Composition API 中,组件的生命周期钩子(如 onMount
、onBeforeMount
等)的调用顺序遵循组件的挂载和卸载流程。以下是它们的调用顺序,以及在父子组件中的表现:
单个组件的生命周期调用顺序
-
onBeforeMount
-
在组件挂载到 DOM 之前调用,此时模板已编译,但尚未渲染到 DOM。
-
-
onMount
-
在组件挂载到 DOM 之后调用,此时可以安全访问 DOM 元素。
-
-
onBeforeUnmount
-
在组件卸载(从 DOM 移除)之前调用,适合清理副作用(如定时器、事件监听)。
-
-
onUnmounted
-
在组件卸载之后调用,此时组件已从 DOM 中移除。
-
父子组件中的调用顺序
挂载阶段(父 → 子)
-
父组件的
onBeforeMount
-
子组件的
onBeforeMount
-
子组件的
onMount
-
父组件的
onMount
卸载阶段(父 → 子)
-
父组件的
onBeforeUnmount
-
子组件的
onBeforeUnmount
-
子组件的
onUnmounted
-
父组件的
onUnmounted
为什么是这样的顺序?
-
挂载时:Vue 需要先确保父组件模板编译完成(父的
onBeforeMount
),然后递归处理子组件的挂载(子的onBeforeMount
和onMount
),最后父组件才能完成挂载(父的onMount
)。 -
卸载时:父组件触发卸载后,需要先清理子组件(保证资源释放),最后再清理自身。
示例代码
父组件
<script setup>
import { onBeforeMount, onMounted, onBeforeUnmount, onUnmounted } from 'vue';
import Child from './Child.vue';
onBeforeMount(() => console.log('父组件 - onBeforeMount'));
onMounted(() => console.log('父组件 - onMounted'));
onBeforeUnmount(() => console.log('父组件 - onBeforeUnmount'));
onUnmounted(() => console.log('父组件 - onUnmounted'));
</script>
<template>
<Child />
</template>
子组件
<script setup>
import { onBeforeMount, onMounted, onBeforeUnmount, onUnmounted } from 'vue';
onBeforeMount(() => console.log('子组件 - onBeforeMount'));
onMounted(() => console.log('子组件 - onMounted'));
onBeforeUnmount(() => console.log('子组件 - onBeforeUnmount'));
onUnmounted(() => console.log('子组件 - onUnmounted'));
</script>
<template>Child Component</template>
控制台输出
父组件 - onBeforeMount
子组件 - onBeforeMount
子组件 - onMounted
父组件 - onMounted
父组件 - onBeforeUnmount
子组件 - onBeforeUnmount
子组件 - onUnmounted
父组件 - onUnmounted
关键点总结
-
生命周期顺序是同步的,遵循从外到内(挂载)和从内到外(卸载)的递归逻辑。
-
子组件的挂载必须在父组件挂载之前完成,而卸载时必须先卸载子组件。
-
如果需要操作 DOM,应在
onMounted
中执行;清理资源应在onBeforeUnmount
或onUnmounted
中执行。
生命周期钩子 | 调用时机 | 典型用途 |
---|---|---|
onBeforeMount | 挂载前 | 访问数据但无法操作 DOM |
onMounted | 挂载后 | 操作 DOM、初始化第三方库 |
onBeforeUpdate | 更新前 | 获取更新前的 DOM 状态 |
onUpdated | 更新后 | 操作更新后的 DOM(慎用) |
onBeforeUnmount | 卸载前 | 清理定时器、事件监听 |
onUnmounted | 卸载后 | 最终清理 |
onActivated | <KeepAlive> 激活 | 恢复组件状态 |
onDeactivated | <KeepAlive> 停用 | 暂停组件任务 |
onErrorCaptured | 捕获错误 | 全局错误处理 |