Vue 2与Vue 3生命周期钩子的对比分析

发布于:2024-04-26 ⋅ 阅读:(23) ⋅ 点赞:(0)

一、概述

Vue 组件实例在创建时经历一系列初始化步骤,Vue 在合适的时机调用特定函数,允许开发者在特定阶段运行自己的代码,这些函数称为生命周期钩子。

二、规律

生命周期可分为四个阶段:创建、挂载、更新、销毁,每个阶段都有两个钩子,一个在前一个在后。

Vue 2 的生命周期:

⭐创建阶段: beforeCreate、created
⭐挂载阶段: beforeMount、mounted
⭐更新阶段:beforeUpdate、updated
⭐销毁阶段: beforeDestroy、destroyed

Vue 3 的生命周期:

⭐创建阶段: setup
⭐挂载阶段: onBeforeMount、onMounted
⭐更新阶段:onBeforeUpdate、onUpdated
⭐卸载阶段: onBeforeUnmount、onUnmounted

常用的钩子: onMounted (挂载完毕)、onUpdated (更新完毕)、onBeforeUnmount (卸载之前)

<template>
  <div class="person">
    <h2>当前求和为:{{ sum }}</h2>
    <button @click="changeSum">点击sum+1</button>
  </div>
</template>

<!-- vue3写法 -->
<script lang="ts" setup name="Person">
import { ref, onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'
// 数据
let sum = ref(0)
// 方法
function changeSum() { sum.value += 1 }
console.log('setup')
// 生命周期钩子
onBeforeMount(() => {   console.log('挂载之前') })
onMounted(() => {       console.log('挂载完毕') })
onBeforeUpdate(() => {  console.log('更新之前') })
onUpdated(() => {       console.log('更新完毕') })
onBeforeUnmount(() => { console.log('卸载之前') })
onUnmounted(() => {     console.log('卸载完毕') })
</script>

三、区别:

1.命名差异:

  • Vue 2 的生命周期钩子以 before, created, beforeMount, mounted, beforeUpdate, updated, activated, deactivated, beforeDestroy, 和 destroyed 等为前缀。
  • Vue 3 的生命周期钩子以 on 为前缀,例如 onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, 和 onUnmounted 等。

2.新增钩子:

  • Vue 3 新增了一些新的生命周期钩子,如 onBeforeMount, onBeforeUpdate, onUpdated, onBeforeUnmount, 和 onUnmounted,用于替代 Vue 2 中的一些 before 和 destroyed 钩子。

3.执行顺序变化:

  • 在Vue 2中,beforeCreate 和 created 钩子在实例初始化之后立即执行。beforeMount 和 mounted 在挂载之前和之后执行,beforeUpdate 和 updated 在数据更新前和后执行,activated 和 deactivated 在keep-alive组件激活和停用时执行,beforeDestroy 和 destroyed 在实例销毁之前和之后执行。
  • 在Vue 3中,生命周期钩子的执行顺序与Vue 2中基本相同,但是由于引入了新的钩子,一些钩子的执行时机可能有所不同。

四、优缺点:

  • Vue 2 的生命周期钩子命名更加简洁直观,易于理解,但是较多的钩子可能会导致混乱。
  • Vue 3 的生命周期钩子命名更加统一,遵循了统一的命名规范,而且新增了一些方便的钩子,使得开发更加灵活。
  • 在执行顺序上,Vue 3 的生命周期钩子更加清晰,但是需要注意一些新增的钩子可能会增加学习成本和理解复杂度。