原理
vue3也提供了Composition API形式的生命周期钩子,与vue2.x中钩子对应关系如下:
beforeCreate =setup()
created =setup()
beforeMount=onBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeUnmountonBeforeUnmount
unmounted===onUnmounted
示例:生命周期
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>