Vue---vue2和vue3的生命周期
核心生命周期对比
生命周期阶段 | Vue 2 钩子 | Vue 3 Composition API |
---|---|---|
初始化 | beforeCreate | 无(使用 setup() 替代) |
初始化完成 | created | 无(使用 setup() 替代) |
挂载前 | beforeMount | onBeforeMount |
挂载完成 | mounted | onMounted |
更新前 | beforeUpdate | onBeforeUpdate |
更新完成 | updated | onUpdated |
卸载前 | beforeDestroy | onBeforeUnmount |
卸载完成 | destroyed | onUnmounted |
错误处理 | errorCaptured | onErrorCaptured |
激活(KeepAlive) | activated | onActivated |
停用(KeepAlive) | deactivated | onDeactivated |
服务端渲染 | serverPrefetch | onServerPrefetch |
Vue 3 核心变化
-
钩子重命名
beforeDestroy
→beforeUnmount
destroyed
→unmounted
- 原因:更准确的语义表达(卸载 vs 销毁)
-
Composition API
- 通过
setup()
函数替代beforeCreate
和created
- 使用
onXxx
形式导入生命周期函数:import { onMounted, onUnmounted } from 'vue'export default {setup() {onMounted(() => {console.log('组件已挂载')})} }
- 通过
-
执行顺序
- Composition API 生命周期比 Options API 更早执行
- 顺序示例:父组件 setup() → 父组件 onBeforeMount → 子组件 setup() → 子组件 onBeforeMount → 子组件 onMounted → 父组件 onMounted
生命周期阶段详解
1. 初始化阶段(setup
/beforeCreate
/created
)
- Vue2:
beforeCreate
:实例初始化,数据观测/事件配置前created
:实例创建完成,可访问data
/methods
,但 DOM 未挂载
- Vue3:
setup()
:替代beforeCreate
和created
,所有组合式逻辑在此初始化- 注意:
setup()
中无法访问this
2. 挂载阶段(onBeforeMount
/onMounted
)
-
onBeforeMount
:- 模板编译完成,虚拟 DOM 已生成,但尚未挂载到真实 DOM
- 使用场景:SSR 中避免 DOM 操作
-
onMounted
:- DOM 已挂载,可操作 DOM 或初始化第三方库(如图表、地图)
- 注意:子组件的
mounted
先于父组件执行
3. 更新阶段(onBeforeUpdate
/onUpdated
)
-
onBeforeUpdate
:- 数据变化导致虚拟 DOM 重新渲染前
- 使用场景:获取更新前的 DOM 状态
-
onUpdated
:- 虚拟 DOM 已重新渲染并应用更新
- 注意:避免在此修改状态,可能导致无限循环
4. 卸载阶段(onBeforeUnmount
/onUnmounted
)
-
onBeforeUnmount
:- 实例销毁前,仍可访问组件状态
- 使用场景:清除定时器、取消事件监听
-
onUnmounted
:- 实例已销毁,所有绑定已移除
- 注意:无法再访问组件内的任何数据
面试重点
Vue3 为什么移除 beforeCreate
和 created
?
setup()
函数统一处理初始化逻辑,更符合组合式 API 设计理念,减少冗余钩子。
setup()
中能访问 this
吗?为什么?
不能。setup()
在实例初始化前执行,此时组件实例尚未创建。
父子组件生命周期执行顺序?
- 挂载阶段:父
beforeMount
→ 子beforeMount
→ 子mounted
→ 父mounted
- 更新阶段:父
beforeUpdate
→ 子beforeUpdate
→ 子updated
→ 父updated
- 卸载阶段:父
beforeUnmount
→ 子beforeUnmount
→ 子unmounted
→ 父unmounted
在 mounted
中修改数据会发生什么?
触发更新流程,依次执行 beforeUpdate
和 updated
钩子。需注意避免死循环。