# Vue3教程 - 12 生命周期函数

生命周期函数也就是组件从创建到销毁的过程中,触发的回调方法,我们可以在回调方法中进行一些操作。

通过学习组件的生命周期函数,我们可以知道在哪个生命周期函数中可以发起网络请求来获取数据,在哪个生命周期函数中才可以获取到组件中的数据,哪个生命周期函数中可以操作DOM。

下面来介绍一下 Vue3 中组件的生命周期函数,这个和 Vue2 中还是有很大的区别的。

但和 Vue2 相同的是,Vue3 中组件的生命周期也分为四个阶段:

  • 创建阶段
  • 挂载阶段
  • 更新阶段
  • 销毁(卸载)阶段

# 12.1 组件的生命周期函数

# 1 创建阶段

在 Vue3 中 setup 中的代码就是创建阶段执行的,所以在 Vue3 中没有针对创建阶段专门的回调函数,直接在 setup 中写就好了:

<!-- setup -->
<script lang="ts" setup>

console.log("创建")

</script>
1
2
3
4
5
6

网络请求在创建阶段发起就可以了。

# 2 挂载阶段

挂载分为挂载前和挂载后两个函数。

在 Vue3 中提供了两个函数 onBeforeMountonMounted ,我们调用者两个函数,并传递函数作为参数,当在挂载前和挂载后,Vue会调用传递的函数。

<!-- setup -->
<script lang="ts" setup>
import { onBeforeMount, onMounted } from 'vue';

// 挂载前
onBeforeMount(() => {
    console.log("挂载前");
});

// 挂载后
onMounted(() => {
    console.log("挂载后");
});

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3 更新阶段

当组件中的数据发生变化时,会触发组件更新,会调用组件的更新的生命周期函数。

更新的生命周期使用 onBeforeUpdateonUpdated 函数的参数来回调。

<template>
    <div>
        <div>{{ count }}</div>
        <button @click="add">add</button>
    </div>
</template>

<!-- setup -->
<script lang="ts" setup>
import { ref, onBeforeUpdate, onUpdated} from 'vue';

let count = ref(0);
function add() {
    count.value++;
}

// 更新前
onBeforeUpdate(() => {
    console.log("更新前");
});

// 更新后
onUpdated(() => {
    console.log("更新后");
});

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

在上面的代码中,每次 add 修改 count,都会触发更新前和更新后的回调函数。

# 4 销毁(卸载)阶段

销毁阶段对应使用的函数是 onBeforeUnmountonUnmounted

Person.vue

<template>
    <div>
        Person组件
    </div>
</template>

<!-- setup -->
<script lang="ts" setup>
import { onBeforeUnmount, onUnmounted } from 'vue';

console.log("创建");

onBeforeUnmount(() => {
    console.log("卸载前");
});

onUnmounted(() => {
    console.log("卸载后");
});

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

在父组件中引入 Person 组件,然后使用 v-if 控制 Person 组件的显示和隐藏,可以看到 Person 组件被创建和销毁。

在父组件中使用 Person 组件。

<template>
  <Person v-if="isShow"/>

  <button @click="isShow=!isShow">切换</button>
</template>

<!-- setup -->
<script lang="ts" setup>
import {ref} from 'vue'

// 引入person组件
import Person from '@/components/Person.vue';

let isShow = ref(true);

</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

上面介绍的组件的声明周期函数并不是全部的函数,还有路由相关的函数,这里并没有列出,在将路由的时候再讲。

# 12.2 父子组件的声明周期函数

# 1 创建和挂载阶段

父子组件在挂载阶段的生命周期函数执行顺序如下:

  1. 父组件 created
  2. 父组件 beforeMount
  3. 每个子组件 created
  4. 每个子组件 beforeMount每个子组件 mounted
  5. 父组件 mounted

需要注意:父组件在子组件挂载之后挂载,所以在 Vue 应用中,最后挂载的是根组件 App 组件。

# 2 更新阶段

父子组件在更新阶段的生命周期函数执行顺序如下:

  1. 父组件 beforeUpdate
  2. 每个子组件 beforeUpdate
  3. 每个子组件 updated
  4. 父组件 updated

# 3 卸载阶段

父子组件在卸载阶段的生命周期函数执行顺序如下:

  1. 每个子组件 beforeUnmount
  2. 每个子组件 unmounted
  3. 父组件 beforeUnmount
  4. 父组件 unmounted