生命周期函数代表的是Vue实例,或者是Vue组件,在网页中各个生命阶段所执行的函数。生命周期函数可以分为创建阶段、挂载阶段、更新阶段以及卸载阶段。
● 创建阶段:setup
● 挂载阶段:onBeforeMount、onMounted
● 更新阶段:onBeforeUpdate、onUpdated
● 卸载阶段:onBeforeUnmount、onUnmounted

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<template>
<h2>count为:{{ count }}</h2>
<button @click="onUpdateCount">更新count</button>
</template>

<script setup>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted
} from 'vue'

// 数据
let count = ref(0)
// 方法
function onUpdateCount() {
count.value += 1
}
console.log('setup')
// 生命周期钩子
onBeforeMount(() => {
console.log('挂载之前')
})
onMounted(() => {
console.log('挂载完毕')
})
onBeforeUpdate(() => {
console.log('更新之前')
})
onUpdated(() => {
console.log('更新完毕')
})
onBeforeUnmount(() => {
console.log('卸载之前')
})
onUnmounted(() => {
console.log('卸载完毕')
})
</script>