vue2 vue3父子组件生命周期

75 阅读1分钟

Vue 2 父子组件生命周期流程

// 父组件
beforeCreate() → created() → beforeMount()
// 子组件
beforeCreate() → created() → beforeMount() → mounted()
// 父组件
mounted()

// 更新beforeUpdate() → 子 beforeUpdate() → 子 updated() → 父 updated()

// 卸载beforeDestroy() → 子 beforeDestroy() → 子 destroyed() → 父 destroyed()

Vue 3 父子组件生命周期流程

// 父组件
setup() → onBeforeMount()
// 子组件
setup() → onBeforeMount() → onMounted()
// 父组件
onMounted()

// 更新onBeforeUpdate() → 子 onBeforeUpdate() → 子 onUpdated() → 父 onUpdated()

// 卸载onBeforeUnmount() → 子 onBeforeUnmount() → 子 onUnmounted() → 父 onUnmounted()

总结

  • 顺序一致:Vue 2 和 Vue 3 的父子组件生命周期执行顺序逻辑相同。
  • 差异在细节:Vue 3 通过组合式 API 提供更灵活的钩子注册方式,并调整了卸载阶段的钩子名称。
  • 组合式 API:在 Vue 3 中,setup() 替代了 beforeCreatecreated,且组合式钩子优先于选项式钩子执行。