生命周期

  • 创建阶段:setup
  • 挂载阶段:onBeforeMount、onMounted
  • 更新阶段:onBeforeUpate、onUpdated
  • 卸载阶段:onBeforeUnmount、onUnmounted

常用钩子:onMounted(挂载完毕)、onUpdated(更新完毕)、onBeforeUnmount(卸载之前)

App.vue(父组件)

<template>
  <div class="app">
    <Person v-if=isShow />
    <button @click="unMounted">卸载子组件</button>
  </div>
</template>

<script lang="ts" setup>
  import { onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref } from 'vue';
  import Person from './components/Person.vue';

  let isShow = ref(true);

  function unMounted() {
    isShow.value = false;
  }

  console.log('父--创建');

  onBeforeMount(() => {
    console.log('父--挂载前');
  }),

  onMounted(() => {
    console.log('父--挂载完毕');
  })

  onBeforeUpdate(() => {
    console.log('父--更新前');
  })

  onUpdated(() => {
    console.log('父--更新完毕');
  })

  onBeforeUnmount(() => {
    console.log('父--卸载前');
  })

  onUnmounted(() => {
    console.log('父--卸载完毕');
  })
</script>

<style scoped>
.app {
  background-color: orange;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}

button {
  margin: 10px 5px;
}
</style>

Person.vue(子组件)

<template>
  <div class="person">
    {{ sum }}
    <button @click="add">求和</button>
  </div>
</template>

<script lang="ts" setup>
  import { onBeforeMount, onBeforeUnmount, onBeforeUpdate, onMounted, onUnmounted, onUpdated, ref } from 'vue';
  let sum = ref(0);

  function add() {
    sum.value += 1;
  }

  console.log('子--创建');

  onBeforeMount(() => {
    console.log('子--挂载前');
  }),

  onMounted(() => {
    console.log('子--挂载完毕');
  })

  onBeforeUpdate(() => {
    console.log('子--更新前');
  })

  onUpdated(() => {
    console.log('子--更新完毕');
  })

  onBeforeUnmount(() => {
    console.log('子--卸载前');
  })

  onUnmounted(() => {
    console.log('子--卸载完毕');
  })
</script>

<style scoped>
.person {
  background-color: skyblue;
  box-shadow: 0 0 10px;
  border-radius: 10px;
  padding: 20px;
}

button {
  margin: 0 5px;
}
</style>

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述


上一篇:链表面试题(C 语言)-2. 反转链表


下一篇:STM32 基于HAL库和STM32cubeIDE的应用教程 (二)--GPIO的使用