Vue3 Lifecycle Hooks

0 阅读2分钟

Vue 3 生命周期钩子详解

Vue 3 的生命周期钩子分为 Options APIComposition 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 APIComposition API触发时机
beforeCreatesetup() 替代组件实例初始化前,无法访问 datamethods
createdsetup() 替代组件实例创建完成,可访问 data/methods,但未挂载 DOM

2. 挂载阶段 (Mounting)

Options APIComposition API触发时机
beforeMountonBeforeMountDOM 挂载前,虚拟 DOM 已生成,但未插入页面
mountedonMountedDOM 挂载完成,可操作真实 DOM,子组件不一定完成挂载

3. 更新阶段 (Updating)

Options APIComposition API触发时机
beforeUpdateonBeforeUpdate数据变化后,虚拟 DOM 重新渲染前(适合获取更新前状态)
updatedonUpdated虚拟 DOM 重新渲染完成,DOM 已更新(避免在此修改状态,可能循环更新)

4. 卸载阶段 (Unmounting)

Options APIComposition API触发时机
beforeUnmountonBeforeUnmount组件卸载前,实例仍可用(清理定时器/事件监听)
unmountedonUnmounted组件卸载完成,所有绑定和监听被移除

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; // 阻止错误向上传播
    });
  }
}

最佳实践

  1. 资源清理:在 onBeforeUnmount/onUnmounted 中移除事件监听、定时器。
  2. 避免在 onUpdated 修改状态:可能导致无限循环更新。
  3. 异步操作:在 onMountedsetup 中发起 API 请求。
  4. DOM 操作:必须在 onMounted 之后进行。
  5. Composition API 优势:逻辑更聚合,同一功能代码集中管理。
// 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 中 beforeDestroydestroyed 已重命名为 onBeforeUnmount/onUnmounted,更语义化。