vue3和vue2生命周期的区别

Vue 3 的生命周期与 Vue 2 相比有以下核心区别,主要体现在 钩子函数命名组合式 API新增功能 上。以下是详细对比和示例说明:


1. 生命周期钩子名称变化

Vue 3 对部分生命周期钩子进行了重命名,以保持命名一致性(添加 on 前缀),并适配组合式 API:

Vue 2 Vue 3 说明
beforeCreate 无(由 setup 替代) setup 函数已包含其逻辑
created 无(由 setup 替代) setup 函数已包含其逻辑
beforeMount onBeforeMount 组件挂载前触发
mounted onMounted 组件挂载后触发
beforeUpdate onBeforeUpdate 数据更新前触发
updated onUpdated 数据更新后触发
beforeDestroy onBeforeUnmount 组件卸载前触发
destroyed onUnmounted 组件卸载后触发
activated onActivated <keep-alive> 缓存组件激活时触发
deactivated onDeactivated <keep-alive> 缓存组件停用时触发
errorCaptured onErrorCaptured 捕获子组件错误时触发

2. 组合式 API 的引入

Vue 3 引入了 组合式 API(Composition API) ,通过 setup() 函数替代 Vue 2 的 beforeCreatecreated 钩子。组合式 API 提供了更灵活的代码组织方式,尤其适合逻辑复用。

Vue 2 示例(选项式 API)
javascript 复制代码
export default {
  data() {
    return { count: 0 };
  },
  created() {
    console.log('created');
  },
  mounted() {
    console.log('mounted');
  }
};
Vue 3 示例(组合式 API)
javascript 复制代码
import { ref, onMounted } from 'vue';

export default {
  setup() {
    const count = ref(0);
    console.log('setup'); // 替代 Vue 2 的 created/beforeCreate

    onMounted(() => {
      console.log('mounted');
    });

    return { count };
  }
};

3. 新增调试钩子

Vue 3 新增了两个调试钩子,用于追踪响应式依赖和渲染触发:

  • onRenderTracked:当渲染函数追踪到响应式依赖时触发。
  • onRenderTriggered:当响应式依赖触发重新渲染时触发。
示例
javascript 复制代码
import { onRenderTracked, onRenderTriggered } from 'vue';

export default {
  setup() {
    onRenderTracked((event) => {
      console.log('追踪依赖:', event.key); // 打印被追踪的响应式属性
    });

    onRenderTriggered((event) => {
      console.log('触发更新:', event.key); // 打印触发更新的响应式属性
    });
  }
};

4. 执行顺序变化(父子组件)

在父子组件的生命周期执行顺序上,Vue 3 与 Vue 2 有差异:

Vue 2 的执行顺序
javascript 复制代码
父 created → 子 created → 子 mounted → 父 mounted
Vue 3 的执行顺序
复制代码
父 setup → 子 setup → 父 onBeforeMount → 子 onBeforeMount → 子 onMounted → 父 onMounted

5. 异步更新机制优化

Vue 3 的更新阶段采用 异步渲染 机制,优化了性能并减少不必要的重复计算。例如,多次修改响应式数据后,Vue 3 会合并更新,避免频繁触发 DOM 操作。

示例
javascript 复制代码
import { ref, onUpdated } from 'vue';

export default {
  setup() {
    const count = ref(0);

    onUpdated(() => {
      console.log('DOM 更新后触发一次');
    });

    // 多次修改 count,只会触发一次 onUpdated
    count.value++;
    count.value++;
  }
};

6. 清理副作用(Cleanup)

在 Vue 3 中,onBeforeUnmount 是清理资源(如定时器、事件监听器)的推荐位置。

Vue 2 示例
javascript 复制代码
export default {
  mounted() {
    this.timer = setInterval(() => {
      console.log('定时器运行');
    }, 1000);
  },
  beforeDestroy() {
    clearInterval(this.timer); // 清理定时器
  }
};
Vue 3 示例
javascript 复制代码
import { onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    let timer = null;

    onMounted(() => {
      timer = setInterval(() => {
        console.log('定时器运行');
      }, 1000);
    });

    onBeforeUnmount(() => {
      clearInterval(timer); // 清理定时器
    });
  }
};

7. 完整对比示例

Vue 2 生命周期钩子
javascript 复制代码
export default {
  data() {
    return { message: 'Hello Vue 2' };
  },
  created() {
    console.log('created');
  },
  mounted() {
    console.log('mounted');
  },
  beforeDestroy() {
    console.log('beforeDestroy');
  }
};
Vue 3 生命周期钩子
javascript 复制代码
import { ref, onMounted, onBeforeUnmount } from 'vue';

export default {
  setup() {
    const message = ref('Hello Vue 3');

    console.log('setup'); // 替代 created/beforeCreate

    onMounted(() => {
      console.log('mounted');
    });

    onBeforeUnmount(() => {
      console.log('onBeforeUnmount'); // 替代 beforeDestroy
    });

    return { message };
  }
};

总结

特性 Vue 2 Vue 3
钩子名称 原始命名(如 beforeCreate 添加 on 前缀(如 onBeforeMount
组合式 API 不支持 支持,通过 setup() 函数组织逻辑
调试钩子 新增 onRenderTracked/onRenderTriggered
执行顺序 父组件先执行 created 父组件先执行 setup
清理资源 beforeDestroy onBeforeUnmount
异步更新优化 同步更新 异步合并更新

最佳实践建议

  1. 优先使用组合式 API:在 Vue 3 中,组合式 API 更适合复杂逻辑的组织和复用。
  2. 清理资源 :始终在 onBeforeUnmount 中移除事件监听器或清除定时器。
  3. 避免在 onUpdated 中修改数据:防止无限更新循环。
  4. 利用调试钩子 :通过 onRenderTrackedonRenderTriggered 优化性能瓶颈。

通过以上对比,可以更清晰地理解 Vue 3 的生命周期设计与 Vue 2 的差异,并在实际开发中灵活应用。

相关推荐
Filotimo_1 天前
2.CSS3.(2).html
前端·css
yinuo1 天前
uniapp微信小程序华为鸿蒙定时器熄屏停止
前端
gnip1 天前
vite中自动根据约定目录生成路由配置
前端·javascript
前端橙一陈1 天前
LocalStorage Token vs HttpOnly Cookie 认证方案
前端·spring boot
~无忧花开~1 天前
JavaScript学习笔记(十五):ES6模板字符串使用指南
开发语言·前端·javascript·vue.js·学习·es6·js
泰迪智能科技011 天前
图书推荐丨Web数据可视化(ECharts 5)(微课版)
前端·信息可视化·echarts
CodeCraft Studio1 天前
借助Aspose.Email,使用 Python 读取 Outlook MSG 文件
前端·python·outlook·aspose·email·msg·python读取msg文件
家里有只小肥猫1 天前
react 初体验2
前端·react.js·前端框架
慧慧吖@1 天前
前端发送请求时,参数的传递格式
前端
L李什么李1 天前
HTML——使用表格制作简历
前端·javascript·html