全部学科
Python全栈
python
NodeJS全栈
nodejs
📅 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 中 beforeDestroydestroyed 更名为 beforeUnmountunmounted

要点总结

  • 生命周期分为创建、更新、卸载三个阶段
  • Composition API 使用 onXXX 函数
  • Options API 使用同名方法选项
  • Vue 3 更新了销毁钩子的命名
想在手机上练习这篇文章的配套题目?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码
← 上一篇 插槽
下一篇 → beforeCreate与created
扫码体验小程序
加载中
想在手机上刷题学习?
使用微信卷王开发者小程序,打开首页顶部扫码功能识别二维码