主题
生命周期
| Vue 2 (Options API) | Vue 3 (Options API) | Vue 3 (Composition API) | 说明 |
|---|---|---|---|
beforeCreate | beforeCreate | ❌ 无(setup 替代) | 实例初始化之后,数据观测之前 |
created | created | ❌ 无(setup 替代) | 实例创建完成,数据观测完成 |
beforeMount | beforeMount | onBeforeMount | 挂载开始之前 |
mounted | mounted | onMounted | 挂载完成 |
beforeUpdate | beforeUpdate | onBeforeUpdate | 数据更新时,DOM 更新前 |
updated | updated | onUpdated | 数据更新后,DOM 更新完成 |
beforeDestroy | beforeUnmount | onBeforeUnmount | 卸载之前 ⭐ 改名了 |
destroyed | unmounted | onUnmounted | 卸载完成 ⭐ 改名了 |
activated | activated | onActivated | keep-alive 组件激活 |
deactivated | deactivated | onDeactivated | keep-alive 组件停用 |
errorCaptured | errorCaptured | onErrorCaptured | 捕获子组件错误 |
| ❌ 无 | ❌ 无 | onRenderTracked | ⭐ 新增:调试用 |
| ❌ 无 | ❌ 无 | onRenderTriggered | ⭐ 新增:调试用 |
| ❌ 无 | ❌ 无 | onServerPrefetch | ⭐ SSR 专用 |
vue2
bash
创建阶段:
└─ beforeCreate(实例初始化后,数据观测前)
↓ 初始化:注入/响应式
└─ created(实例创建完成,可访问 data、methods)
↓ 编译模板
↓ 判断 el、template
挂载阶段:
└─ beforeMount(挂载前,虚拟 DOM 已创建)
↓ 创建 vm.$el 并替换 el
└─ mounted(DOM 挂载完成,可访问 $el)
更新阶段:
└─ beforeUpdate(数据更新,DOM 更新前)
↓ 虚拟 DOM 重新渲染和打补丁
└─ updated(DOM 更新完成)
销毁阶段:
└─ beforeDestroy(销毁前,实例仍可用)
↓ 移除监听器、子组件、事件
└─ destroyed(实例销毁完成)vue3
bash
创建阶段:
└─ setup()(❗取代了 beforeCreate 和 created)
↓ 响应式数据、computed、watch 等
挂载阶段:
└─ onBeforeMount(挂载前)
↓ 渲染虚拟 DOM
└─ onMounted(DOM 挂载完成)
更新阶段:
└─ onBeforeUpdate(数据更新,DOM 更新前)
↓ 虚拟 DOM 对比和打补丁
└─ onUpdated(DOM 更新完成)
卸载阶段:
└─ onBeforeUnmount(卸载前,实例仍可用)
↓ 清理副作用、定时器、监听器
└─ onUnmounted(卸载完成)