vue3的生命周期钩子有哪些变化
在 Vue 3 中,生命周期钩子发生了一些变化,主要是为了与 Composition API 更好地集成。以下是 Vue 3 中生命周期钩子的变化和对应的 <script setup> 示例:
Vue 3 生命周期钩子的变化
beforeCreate和created
-
在 Vue 3 中,
beforeCreate和created被合并到了setup函数中。 -
在
setup中直接编写的代码,相当于created钩子中的逻辑。 -
beforeCreate的逻辑可以通过直接在setup中编写代码来实现。
- 其他生命周期的命名变化
-
Vue 3 中的生命周期钩子名称与 Vue 2 类似,但为了与 Composition API 保持一致,添加了
on前缀。 -
例如:
-
beforeMount->onBeforeMount -
mounted->onMounted -
beforeUpdate->onBeforeUpdate -
updated->onUpdated -
beforeUnmount->onBeforeUnmount -
unmounted->onUnmount
-
- 新增的生命周期钩子
-
onRenderTracked:在渲染过程中追踪到响应式依赖时调用。 -
onRenderTriggered:在响应式依赖触发重新渲染时调用。
Vue 3 生命周期钩子列表
| Vue 2 钩子 | Vue 3 钩子 | 说明 |
|---|---|---|
| beforeCreate | 无 | 被 setup 替代,直接在 setup 中编写代码。 |
| created | 无 | 被 setup 替代,直接在 setup 中编写代码。 |
| beforeMount | onBeforeMount | 组件挂载到 DOM 之前调用。 |
| mounted | onMounted | 组件挂载到 DOM 之后调用。 |
| beforeUpdate | onBeforeUpdate | 组件更新之前调用。 |
| updated | onUpdated | 组件更新之后调用。 |
| beforeUnmount | onBeforeUnmount | 组件卸载之前调用(Vue 2 中为 beforeDestroy)。 |
| unmounted | onUnmounted | 组件卸载之后调用(Vue 2 中为 destroyed)。 |
| activated | onActivated | 被 <keep-alive> 缓存的组件激活时调用。 |
| deactivated | onDeactivated | 被 <keep-alive> 缓存的组件停用时调用。 |
| errorCaptured | onErrorCaptured | 捕获子组件错误时调用。 |
| renderTracked | onRenderTracked | 响应式依赖被追踪时调用(仅开发模式)。 |
| renderTriggered | onRenderTriggered | 响应式依赖触发重新渲染时调用(仅开发模式)。 |
<script setup> 中使用生命周期钩子
在 <script setup> 中,可以通过从 vue 中导入生命周期钩子函数来使用它们。
<script setup>
import {
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
onActivated,
onDeactivated,
onErrorCaptured,
onRenderTracked,
onRenderTriggered
} from 'vue';
// 组件挂载前
onBeforeMount(() => {
console.log('onBeforeMount');
});
// 组件挂载后
onMounted(() => {
console.log('onMounted');
});
// 组件更新前
onBeforeUpdate(() => {
console.log('onBeforeUpdate');
});
// 组件更新后
onUpdated(() => {
console.log('onUpdated');
});
// 组件卸载前
onBeforeUnmount(() => {
console.log('onBeforeUnmount');
});
// 组件卸载后
onUnmounted(() => {
console.log('onUnmounted');
});
// 被 <keep-alive> 缓存的组件激活时
onActivated(() => {
console.log('onActivated');
});
// 被 <keep-alive> 缓存的组件停用时
onDeactivated(() => {
console.log('onDeactivated');
});
// 捕获子组件错误时
onErrorCaptured(() => {
console.log('onErrorCaptured');
});
// 响应式依赖被追踪时(开发模式)
onRenderTracked(() => {
console.log('onRenderTracked');
});
// 响应式依赖触发重新渲染时(开发模式)
onRenderTriggered(() => {
console.log('onRenderTriggered');
});
</script>
<template>
<div>生命周期钩子示例</div>
</template>
总结
-
Vue 3 的生命周期钩子通过
on前缀与 Composition API 集成。 -
在
<script setup>中,可以直接导入并使用这些钩子函数。 -
beforeCreate和created被setup替代,无需显式定义。
更多vue相关插件及后台管理模板可访问vue admin reference,代码详情请访问github