Vue3生命周期

Vue3 中取消了 beforeCreate 和 created 这两个生命周期函数,其他生命周期函数的名字也发生了改变,详细说明如表 12-1 所示。

Vue2.X Vue3.X

beforeMount

onBeforeMount

mounted

onMounted

beforeUpdate

onBeforeUpdate

updated

onUpdated

beforeDestroy

onBeforeUnmount

destroyed

onUnmounted

生命周期函数使用方法:在 Vue3 和 Vue2 中使用生命周期函数的方式是不同的,在 Vue2 中所有的生命周期函数都可以直接使用,但在 Vue3 中要遵循两个规则。

(1)使用一个生命周期函数前需先进行引用。 (2)生命周期函数是在setup中使用的。

案例:单击按钮实现数字新增,触发 onUpdated 生命周期函数,代码如下。

<template>
  <div>
    <h2>触发 onUpdated 生命周期函数</h2>
    <p>{{ num }}</p>
    <button @click="addOne">+1</button>
  </div>
</template>

<script>
// 1. 引用 onUpdated
import { onUpdated, ref } from "vue";

export default {
  setup() {
    var num = ref(0);

    function addOne() {
      num.value++;
    }

    // 2. onUpdated 在 setup 中使用
    onUpdated(() => {
      console.log("触发 onUpdated 生命周期函数");
    });

    return { num, addOne };
  }
};
</script>