原理
vue3也提供了Composition API形式的生命周期钩子,与vue2.x中钩子对应关系如下:
beforeCreate =setup()
created =setup()
beforeMount=onBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeUnmountonBeforeUnmount
unmounted===onUnmounted文章来源:https://www.toymoban.com/news/detail-660024.html
示例:生命周期
HomeView.vue
<template>
<div ref="showDiv" v-text="username"></div>
<button @click="changeTitle">更新数据</button>
</template>
<script lang="ts" setup>
import {
ref,
onBeforeMount,
onMounted,
onBeforeUpdate,
onUpdated,
onBeforeUnmount,
onUnmounted,
} from "vue";
//获取页面组件
const showDiv = ref();
const username = ref("张三");
//修改名称
const changeTitle = () => {
username.value = "zhangsan";
};
console.log("setup:开始创建组件之前,在beforeCreate和created之前执行");
onBeforeMount(() => {
console.log(
"onBeforeMount:组件挂载到节点上之前执行",
showDiv.value?.innerText
);
});
onMounted(() => {
console.log("onMounted:组件挂载到节点上之后执行", showDiv.value?.innerText);
});
onBeforeUpdate(() => {
console.log("onBeforeUpdate:组件更新之前执行", showDiv.value?.innerText);
});
onUpdated(() => {
console.log("onUpdated:组件更新完成之后执行", showDiv.value?.innerText);
});
onBeforeUnmount(() => {
console.log("onBeforeUnmount:组件卸载之前执行", showDiv.value?.innerText);
});
onUnmounted(() => {
console.log("onUnmounted:组件卸载完成之后执行", showDiv.value?.innerText);
});
</script>
App.vue
<template>
<div>
<HomeView v-if="isDestroy" ></HomeView>
<button @click="destroyShowDiv">用v-if模拟组件销毁的过程</button>
</div>
<!-- <router-view /> -->
</template>
<script setup lang="ts">
import { ref } from "vue";
import HomeView from './views/HomeView.vue';
const isDestroy = ref(true);
//用v-if模拟组件销毁的过程
const destroyShowDiv = () => {
isDestroy.value = false;
};
</script>
结果:
文章来源地址https://www.toymoban.com/news/detail-660024.html
到了这里,关于vue3生命周期的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!