生命周期概述
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 更新了销毁钩子的命名
📝 发现内容有误?点击此处直接编辑