首页/ 学科题库/ vue/ 生命周期概述
vue 实战教程

生命周期概述

2026-05-20 约 7 分钟 juanwangdev

生命周期概述

Vue 组件实例在创建过程中经历一系列初始化步骤。

生命周期阶段

JavaScript
创建阶段
├── setup() - Composition API 入口
├── beforeCreate - 实例初始化后
├── created - 实例创建完成
├── beforeMount - 挂载前
└── mounted - 挂载完成

更新阶段
├── beforeUpdate - 数据变化,DOM更新前
└── updated - DOM更新完成

卸载阶段
├── beforeUnmount - 卸载前
└── unmounted - 卸载完成

Composition API 钩子

JavaScript
import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted
} from 'vue'

export default {
  setup() {
    onMounted(() => console.log('mounted'))
    onUnmounted(() => console.log('unmounted'))
  }
}

Options API 钩子

text
export default {
  mounted() {
    console.log('mounted')
  },
  unmounted() {
    console.log('unmounted')
  }
}

生命周期流程图

text
setup/beforeCreate → created → beforeMount → mounted → beforeUpdate → updated → beforeUnmount → unmounted

Vue 3 中 beforeDestroy 和 destroyed 更名为 beforeUnmount 和 unmounted。

要点总结

  • 生命周期分为创建、更新、卸载三个阶段
  • Composition API 使用 onXXX 函数
  • Options API 使用同名方法选项
  • Vue 3 更新了销毁钩子的命名
想在手机上练这篇的配套题目?
使用微信 卷王开发者小程序/App,首页顶部扫一扫识别下方二维码,即可解锁本讲对应真题与错题本。
了解产品 App
← 上一篇 插槽 下一篇 → beforeCreate与created