vue3的生命周期函数

Vue3 生命周期函数调用顺序解析

在 Vue 3 的 Composition API 中,组件的生命周期钩子(如 onMountonBeforeMount 等)的调用顺序遵循组件的挂载和卸载流程。以下是它们的调用顺序,以及在父子组件中的表现:


单个组件的生命周期调用顺序

  1. onBeforeMount

    • 在组件挂载到 DOM 之前调用,此时模板已编译,但尚未渲染到 DOM。

  2. onMount

    • 在组件挂载到 DOM 之后调用,此时可以安全访问 DOM 元素。

  3. onBeforeUnmount

    • 在组件卸载(从 DOM 移除)之前调用,适合清理副作用(如定时器、事件监听)。

  4. onUnmounted

    • 在组件卸载之后调用,此时组件已从 DOM 中移除。


父子组件中的调用顺序

挂载阶段(父 → 子)
  1. 父组件的 onBeforeMount

  2. 子组件的 onBeforeMount

  3. 子组件的 onMount

  4. 父组件的 onMount

卸载阶段(父 → 子)
  1. 父组件的 onBeforeUnmount

  2. 子组件的 onBeforeUnmount

  3. 子组件的 onUnmounted

  4. 父组件的 onUnmounted


为什么是这样的顺序?

  • 挂载时:Vue 需要先确保父组件模板编译完成(父的 onBeforeMount),然后递归处理子组件的挂载(子的 onBeforeMountonMount),最后父组件才能完成挂载(父的 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

关键点总结

  1. 生命周期顺序是同步的,遵循从外到内(挂载)和从内到外(卸载)的递归逻辑。

  2. 子组件的挂载必须在父组件挂载之前完成,而卸载时必须先卸载子组件。

  3. 如果需要操作 DOM,应在 onMounted 中执行;清理资源应在 onBeforeUnmountonUnmounted 中执行。

生命周期钩子调用时机典型用途
onBeforeMount挂载前访问数据但无法操作 DOM
onMounted挂载后操作 DOM、初始化第三方库
onBeforeUpdate更新前获取更新前的 DOM 状态
onUpdated更新后操作更新后的 DOM(慎用)
onBeforeUnmount卸载前清理定时器、事件监听
onUnmounted卸载后最终清理
onActivated<KeepAlive> 激活恢复组件状态
onDeactivated<KeepAlive> 停用暂停组件任务
onErrorCaptured捕获错误全局错误处理

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值