Vue2 生命周期钩子
Vue2 的生命周期钩子主要有以下8个:
- beforeCreate - 实例初始化之后,数据观测(data observer)和事件配置之前调用
- created - 实例创建完成后调用,此时已完成数据观测,但尚未挂载
- beforeMount - 在挂载开始之前被调用,相关的 render 函数首次被调用
- mounted - 实例挂载到DOM后调用
- beforeUpdate - 数据更新时调用,发生在虚拟DOM重新渲染和打补丁之前
- updated - 数据更改导致的虚拟DOM重新渲染和打补丁之后调用
- beforeDestroy - 实例销毁之前调用
- destroyed - 实例销毁后调用
Vue3 生命周期变化
Vue3 的生命周期主要有以下变化:
-
名称变化:
beforeDestroy改为beforeUnmountdestroyed改为unmounted
-
新增钩子:
onRenderTracked- 调试钩子,跟踪虚拟DOM重新渲染时调用onRenderTriggered- 调试钩子,当虚拟DOM重新渲染被触发时调用
-
组合式API中的用法:
在setup()函数中使用生命周期钩子需要加上"on"前缀:javascript
复制
import { onMounted, onUpdated, onUnmounted } from 'vue' setup() { onMounted(() => { console.log('组件已挂载') }) onUpdated(() => { console.log('组件已更新') }) onUnmounted(() => { console.log('组件已卸载') }) }
对应关系表
| Vue2 生命周期 | Vue3 生命周期 | 组合式API中的等价物 |
|---|---|---|
| beforeCreate | setup() | - |
| created | setup() | - |
| beforeMount | onBeforeMount | onBeforeMount |
| mounted | onMounted | onMounted |
| beforeUpdate | onBeforeUpdate | onBeforeUpdate |
| updated | onUpdated | onUpdated |
| beforeDestroy | onBeforeUnmount | onBeforeUnmount |
| destroyed | onUnmounted | onUnmounted |
| - | onActivated | onActivated |
| - | onDeactivated | onDeactivated |
| - | onErrorCaptured | onErrorCaptured |
| - | onRenderTracked | onRenderTracked |
| - | onRenderTriggered | onRenderTriggered |
重要说明
- setup()替代了beforeCreate和created:在Vue3中,setup()函数在beforeCreate和created之前运行,因此这两个钩子在组合式API中没有直接对应的钩子。
- 新增的Keep-Alive相关钩子:Vue3新增了
onActivated和onDeactivated来处理被<keep-alive>缓存的组件的状态。 - 调试钩子:
onRenderTracked和onRenderTriggered是Vue3新增的调试钩子,用于跟踪组件的重新渲染。 - 错误处理:
onErrorCaptured是Vue3中用于捕获子组件错误的钩子。
Vue3的生命周期设计更加一致和清晰,特别是在组合式API中,通过导入函数的方式使用生命周期钩子使得代码组织更加灵活。