Vue 3 生命周期钩子详解
Vue 3 的生命周期钩子分为 Options API 和 Composition API 两种使用方式,核心流程相同但语法有差异。以下是完整生命周期流程和每个钩子的详细说明:
Composition API 生命周期流程图
<template>
<div>实际参数{{count}}</div>
</template>
<script setup lang="ts">
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
const count= ref<number>(0)
let timer = ref<any>(null)
onBeforeMount(() => {
console.log('DOM挂载前')
})
onMounted(() => {
console.log('DOM已挂载')
timer.value = setInterval(()=> {
count.value += 1
},1000)
})
onBeforeUpdate(() => {
console.log('数据更新前', count.value)
})
onUpdated(() => {
console.log('数据更新后')
})
onBeforeUnmount(() => {
console.log('组件卸载前')
})
onUnmounted(() => {
console.log('组件已卸载')
})
</script>
1. 创建阶段 (Creation)
Options API | Composition API | 触发时机 |
---|
beforeCreate | setup() 替代 | 组件实例初始化前,无法访问 data 和 methods |
created | setup() 替代 | 组件实例创建完成,可访问 data /methods ,但未挂载 DOM |
2. 挂载阶段 (Mounting)
Options API | Composition API | 触发时机 |
---|
beforeMount | onBeforeMount | DOM 挂载前,虚拟 DOM 已生成,但未插入页面 |
mounted | onMounted | DOM 挂载完成,可操作真实 DOM,子组件不一定完成挂载 |
3. 更新阶段 (Updating)
Options API | Composition API | 触发时机 |
---|
beforeUpdate | onBeforeUpdate | 数据变化后,虚拟 DOM 重新渲染前(适合获取更新前状态) |
updated | onUpdated | 虚拟 DOM 重新渲染完成,DOM 已更新(避免在此修改状态,可能循环更新) |
4. 卸载阶段 (Unmounting)
Options API | Composition API | 触发时机 |
---|
beforeUnmount | onBeforeUnmount | 组件卸载前,实例仍可用(清理定时器/事件监听) |
unmounted | onUnmounted | 组件卸载完成,所有绑定和监听被移除 |
5. 特殊钩子
钩子 | 用途 |
---|
onErrorCaptured | 捕获子孙组件的错误(类似 React ErrorBoundary) |
onRenderTracked | 开发调试:跟踪虚拟 DOM 重新渲染时的依赖 |
onRenderTriggered | 开发调试:追踪触发重新渲染的依赖变化 |
onActivated | <keep-alive> 缓存的组件激活时调用 |
onDeactivated | <keep-alive> 缓存的组件停用时调用 |
import { onErrorCaptured } from 'vue';
export default {
setup() {
onErrorCaptured((err, instance, info) => {
console.error("子组件错误:", err);
return false;
});
}
}
最佳实践
- 资源清理:在
onBeforeUnmount/onUnmounted
中移除事件监听、定时器。
- 避免在
onUpdated
修改状态:可能导致无限循环更新。
- 异步操作:在
onMounted
或 setup
中发起 API 请求。
- DOM 操作:必须在
onMounted
之后进行。
- Composition API 优势:逻辑更聚合,同一功能代码集中管理。
export default {
setup() {
const data = ref(null);
onMounted(fetchData);
onUnmounted(cleanup);
function fetchData() {
axios.get('/api').then(res => data.value = res);
}
function cleanup() { }
return { data };
}
}
💡 提示:Vue 3 中 beforeDestroy
和 destroyed
已重命名为 onBeforeUnmount/onUnmounted
,更语义化。