Vue---vue2和vue3的生命周期

0 阅读2分钟

核心生命周期对比

生命周期阶段Vue 2 钩子Vue 3 Composition API
​初始化​beforeCreate无(使用 setup() 替代)
​初始化完成​created无(使用 setup() 替代)
​挂载前​beforeMountonBeforeMount
​挂载完成​mountedonMounted
​更新前​beforeUpdateonBeforeUpdate
​更新完成​updatedonUpdated
​卸载前​beforeDestroyonBeforeUnmount
​卸载完成​destroyedonUnmounted
​错误处理​errorCapturedonErrorCaptured
​激活(KeepAlive)​activatedonActivated
​停用(KeepAlive)​deactivatedonDeactivated
​服务端渲染​serverPrefetchonServerPrefetch

 Vue 3 核心变化​

  1. ​钩子重命名​

    • beforeDestroy → beforeUnmount
    • destroyed → unmounted
    • ​原因​​:更准确的语义表达(卸载 vs 销毁)
  2. ​Composition API​

    • 通过 setup() 函数替代 beforeCreate 和 created

    • 使用 onXxx 形式导入生命周期函数:

      import { onMounted, onUnmounted } from 'vue'
      
      export default {
        setup() {
          onMounted(() => {
            console.log('组件已挂载')
          })
        }
      }
      

  3. ​执行顺序​

    • 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 钩子。需注意避免死循环。