文章仅供学习,如有任何问题欢迎指正。
在Vue3中,分别有着选项是Api和组合式Api,其生命周期也有着不同, 其中对于选项式Api基本与Vue2保持一致
- beforeCreate:在实例被创建之前调用。
- created:在实例创建完成后立即调用。
- beforeMount:在挂载开始之前调用。
- mounted:在挂载完成后调用。
- beforeUpdate:在数据更新之前调用。
- updated:在数据更新之后调用。
- beforeUnmount:在卸载之前调用。
- unmounted:在卸载之后调用。
而对于Vue3中发生了些许变化
setup
:在组件实例化之前调用。在setup
函数中可以设置响应式状态、引入其他模块等。onBeforeMount
:在组件挂载之前调用。onMounted
:在组件挂载之后调用。onBeforeUpdate
:在组件更新之前调用。onUpdated
:在组件更新之后调用。onBeforeUnmount
:在组件卸载之前调用。onUnmounted
:在组件卸载之后调用。
但是需要注意的是,Vue 3的组合式API中的生命周期钩子函数是基于函数调用的方式,而不再是作为组件选项的一部分。这意味着在使用组合式API时,不再像Vue 2中那样直接定义beforeCreate
、created
等钩子函数,而是通过在setup
函数中返回一个对象,对象中包含相应的生命周期钩子函数。
组合式
<template>
<div>{{ message }}</div>
</template>
<script>
import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue';
export default {
setup() {
const message = 'Hello, Vue 3!';
// 组件创建前调用
onBeforeMount(() => {
console.log('Component before mount');
});
// 组件创建后调用
onMounted(() => {
console.log('Component mounted');
});
// 组件更新前调用
onBeforeUpdate(() => {
console.log('Component before update');
});
// 组件更新后调用
onUpdated(() => {
console.log('Component updated');
});
// 组件卸载前调用
onBeforeUnmount(() => {
console.log('Component before unmount');
});
// 组件卸载后调用
onUnmounted(() => {
console.log('Component unmounted');
});
return {
message,
};
},
};
</script>
选项式
<template>
<div>{{ message }}</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue 3!',
};
},
// 组件创建前调用
beforeCreate() {
console.log('Component before create');
},
// 组件创建后调用
created() {
console.log('Component created');
},
// 组件挂载前调用
beforeMount() {
console.log('Component before mount');
},
// 组件挂载后调用
mounted() {
console.log('Component mounted');
},
// 组件更新前调用
beforeUpdate() {
console.log('Component before update');
},
// 组件更新后调用
updated() {
console.log('Component updated');
},
// 组件卸载前调用
beforeUnmount() {
console.log('Component before unmount');
},
// 组件卸载后调用
unmounted() {
console.log('Component unmounted');
},
};
</script>
示例中,我们使用了onBeforeMount
、onMounted
、onBeforeUpdate
、onUpdated
、onBeforeUnmount
和onUnmounted
这些组合式API提供的生命周期函数来模拟类似于选项式API的生命周期钩子函数的功能。这些函数分别在组件的不同生命周期阶段执行相应的逻辑。需要注意的是,使用组合式API时,不再需要在setup
函数中使用return
返回数据,直接在setup
函数内定义响应式数据即可。