Vue2与Vue3生命周期实现对比分析
生命周期钩子概述
Vue2生命周期钩子
// Vue2生命周期钩子示例
export default {
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {},
beforeUpdate() {},
updated() {},
beforeDestroy() {},
destroyed() {}
}
Vue3生命周期钩子
// Vue3 Options API生命周期钩子
export default {
beforeCreate() {},
created() {},
beforeMount() {},
mounted() {},
beforeUpdate() {},
updated() {},
beforeUnmount() {}, // 改名
unmounted() {} // 改名
}
// Vue3 Composition API生命周期钩子
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
export default {
setup() {
onBeforeMount(() => {})
onMounted(() => {})
onBeforeUpdate(() => {})
onUpdated(() => {})
onBeforeUnmount(() => {})
onUnmounted(() => {})
}
}
实现原理对比
Vue2生命周期实现
// Vue2生命周期实现示例
function callHook(vm, hook) {
const handlers = vm.$options[hook]
if (handlers) {
for (let i = 0; i < handlers.length; i++) {
handlers[i].call(vm)
}
}
}
// 在实例化过程中调用
function Vue() {
// ...
callHook(vm, 'beforeCreate')
initState(vm)
callHook(vm, 'created')
// ...
}
主要特点
- 基于Options API
- 钩子函数与实例强绑定
- 执行顺序固定
- 上下文this指向实例
Vue3生命周期实现
// Vue3生命周期实现示例
function createHook(lifecycle) {
return (hook, target = currentInstance) => {
injectHook(lifecycle, hook, target)
}
}
export const onBeforeMount = createHook(LifecycleHooks.BEFORE_MOUNT)
export const onMounted = createHook(LifecycleHooks.MOUNTED)
// ...
主要特点
- 支持Options API和Composition API
- 基于依赖注入
- 更灵活的组织方式
- 更好的类型推导
执行流程对比
Vue2执行流程
-
new Vue()
- beforeCreate
- 初始化数据
- created
- 编译模板
- beforeMount
- 创建DOM
- mounted
-
数据更新
- beforeUpdate
- 更新DOM
- updated
-
销毁
- beforeDestroy
- 清理
- destroyed
Vue3执行流程
-
createApp()
- beforeCreate
- setup()
- created
- 编译模板
- beforeMount
- 创建DOM
- mounted
-
数据更新
- beforeUpdate
- 更新DOM
- updated
-
销毁
- beforeUnmount
- 清理
- unmounted
组合式API的生命周期
特点
- 更好的逻辑复用
- 更灵活的组织方式
- 更好的类型推导
- 可以多次调用
使用示例
// Vue3组合式API生命周期使用示例
import { onMounted, onUpdated, onUnmounted } from 'vue'
export default {
setup() {
// 可以多次调用
onMounted(() => {
console.log('mounted 1')
})
onMounted(() => {
console.log('mounted 2')
})
// 可以和逻辑关注点一起组织
function useFeature() {
onMounted(() => {
// feature mounted logic
})
onUnmounted(() => {
// feature cleanup logic
})
}
useFeature()
}
}
优缺点对比
Vue2生命周期
优点:
- 使用简单直观
- 执行顺序可预测
- 代码组织集中
缺点:
- 逻辑复用困难
- 代码组织不够灵活
- 类型推导不够友好
Vue3生命周期
优点:
- 支持逻辑复用
- 更灵活的代码组织
- 更好的类型推导
- 可以按需引入
缺点:
- 学习曲线增加
- 代码组织可能分散
- 需要注意执行顺序
最佳实践
Vue2最佳实践
- 合理使用生命周期钩子
- 避免在生命周期中做太多事情
- 注意内存泄漏
Vue3最佳实践
- 按照关注点组织代码
- 使用组合式函数复用逻辑
- 注意cleanup函数
迁移建议
- beforeDestroy -> beforeUnmount
- destroyed -> unmounted
- 考虑使用组合式API重构
- 注意setup()的使用时机
总结
Vue3在生命周期实现上进行了重大改进,通过引入Composition API,提供了更灵活的代码组织方式和更好的逻辑复用能力。虽然增加了一定的学习成本,但带来的收益是显著的。对于新项目,建议优先考虑使用Composition API;对于现有项目,可以渐进式地引入Composition API进行重构。