作为前端程序员,你是否曾被Vue生命周期钩子的执行顺序绕晕?是否在Vue2升级Vue3时对生命周期的变化感到困惑?今天用5分钟帮你建立完整的生命周期知识体系!
一、先抛结论(懒人直通车)
✅ Vue2生命周期流程:
beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeDestroy → destroyed
✅ Vue3生命周期流程:
setup → onBeforeMount → onMounted → onBeforeUpdate → onUpdated → onBeforeUnmount → onUnmounted
✅ 父子组件执行顺序(核心差异点):
Vue2:父create → 子create → 子mount → 父mount
Vue3:父setup → 子setup → 子mount → 父mount
二、生命周期对比表(建议收藏)
| 阶段 | Vue2 | Vue3 (Composition API) |
|---|---|---|
| 初始化 | beforeCreate | setup |
| 响应式数据就绪 | created | setup |
| DOM挂载前 | beforeMount | onBeforeMount |
| DOM挂载完成 | mounted | onMounted |
| 数据更新前 | beforeUpdate | onBeforeUpdate |
| 数据更新完成 | updated | onUpdated |
| 组件销毁前 | beforeDestroy | onBeforeUnmount |
| 组件销毁完成 | destroyed | onUnmounted |
三、父子组件生命周期执行顺序(重点!)
🎯 Vue2 执行顺序(经典瀑布流)
// 父组件执行
父beforeCreate → 父created → 父beforeMount
// 子组件执行
→ 子beforeCreate → 子created → 子beforeMount → 子mounted
// 父组件继续
→ 父mounted
🚀 Vue3 执行顺序(setup先行)
// 父组件执行
父setup → 父onBeforeMount
// 子组件执行
→ 子setup → 子onBeforeMount → 子onMounted
// 父组件继续
→ 父onMounted
关键差异:Vue3的setup阶段代替了beforeCreate/created,且子组件的setup会在父组件onBeforeMount前完成!
四、实际场景应用指南
1. 数据初始化
- Vue2:在created中发起异步请求
- Vue3:直接在setup中使用async/await(需配合Suspense组件)
2. DOM操作
- Vue2/Vue3通用:在mounted/onMounted中操作DOM
// Vue3示例
onMounted(() => {
const el = document.getElementById('myElement')
el.style.color = 'red'
})
3. 组件通信
- 父子传值:父beforeUpdate → 子beforeUpdate → 子updated → 父updated
- 重要原则:子组件的更新不会触发父组件的重新渲染!
五、底层原理揭秘(高能预警)
1. 生命周期本质
每个钩子对应Vue内部渲染流水线的特定阶段:
beforeCreate:尚未初始化响应式系统created:已完成data/methods的绑定mounted:已完成虚拟DOM → 真实DOM的挂载
2. Vue3的颠覆性改变
- Proxy代理:Vue3使用Proxy实现响应式,在setup阶段即完成数据绑定
- 渲染优化:引入PatchFlags进行靶向更新,影响beforeUpdate/updated触发频率
- Tree-Shaking:按需导入生命周期函数,减小打包体积
3. 父子顺序原理
六、最佳实践(避坑指南)
- 避免在beforeMount/mounted中修改响应式数据 → 可能导致无限循环
- Vue3的onMounted中获取DOM最安全
- 父子组件通信时,推荐使用watchEffect替代updated钩子
- 销毁阶段务必在onBeforeUnmount中清除定时器/事件监听
七、升级Vue3必看变化
beforeDestroy→onBeforeUnmount(语义更清晰)- 移除
activated/deactivated→ 改用<KeepAlive>组件的生命周期 - Composition API的setup函数替代了大部分选项式API
结尾彩蛋 🎁
关注公众号【鱼樱AI实验室】回复【DeepSeek前端】免费获取:前端专用Prompt模板库PDF
回复【Vue3】免费获取徒手思考的:Vue3完整学习大纲!!!!不让你错过任何一个经典的知识点
如果觉得有帮助,记得点赞⭐收藏 ➕ 关注!下期预告:《Vue3响应式原理深度剖析:从Proxy到依赖收集的全链路实现》 🚀
💡 本文价值:帮你节省查阅官方文档的2小时,理清实际开发中的生命周期困惑。转发给团队伙伴一起提升开发效率吧!