生命周期
约 542 字大约 2 分钟
2025-08-08
1. 初始渲染阶段(挂载)
在应用的初始化渲染阶段,执行顺序 为:
- 父组件
beforeCreate
- 父组件
created
- 父组件
beforeMount
- 子组件
beforeCreate
- 子组件
created
- 子组件
beforeMount
- 子组件
mounted
- 父组件
mounted
2. 更新阶段(父组件状态变化)
由父组件引发的子组件更新,一般是子组件先更新,父组件后更新。
执行顺序:
- 父组件
beforeUpdate
- 子组件
beforeUpdate
- 子组件
updated
- 父组件
updated
3. 卸载阶段(销毁)
销毁父组件时,一般是先销毁子组件,清理对应的依赖和订阅更新,然后销毁父组件。
执行顺序:
- 父组件
beforeUnmount
- 子组件
beforeUnmount
- 子组件
unmounted
- 父组件
unmounted
示例代码
以下是一个 Vue 3 生命周期钩子的示例代码:
<template>
<div class="person">
<h2>当前求和为:{{ sum }}</h2>
<button @click="changeSum">点我sum+1</button>
</div>
</template>
<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>
更新日志
2025/8/24 08:17
查看所有更新日志
e7112
-1于