vue3生命周期

原理

vue3生命周期_第1张图片
vue3也提供了Composition API形式的生命周期钩子,与vue2.x中钩子对应关系如下:
beforeCreate =setup()
created =setup()
beforeMount
=onBeforeMount
mounted
onMounted
beforeUpdateonBeforeUpdate
updated
onUpdated
beforeUnmount
onBeforeUnmount
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>
  
  
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>

结果:

vue3生命周期_第2张图片

你可能感兴趣的:(Vue,vue3,生命周期)