preface

“This is the first day of my participation in the First Challenge 2022. For details: First Challenge 2022”

Off-topic: Chinese New Year, the recent mood super good, but also specially to take a festive Hanfu photos, back home mom and dad to do the food is also very fragrant, help to do housework, free time to play games to see “Journey to the West”, sleep in will not be scolded, whoo-woo super satisfied ~

Today my personal learning life cycles of vue3 le again record again, this paper resources: | official document life cycle hook

What is the life cycle

“A Vue instance has a full life cycle, from the start of creating initialization data, compiling templates, mounting DOM, rendering to update, rendering to uninstall, and so on. We call this the life cycle of a Vue.”

Refer to Vue3 life cycle diagram:

Lifecycle hook

During the lifecycle, functions called lifecycle hooks are also run. We can fire different hook functions at different stages, which gives us the opportunity to add our own code at different stages. Mounted hooks can be used to execute code after an instance has been mounted:

Vue.createApp({
  mounted() {
    console.log('mounted-- execute after page is mounted ')}})Copy the code

Vue3 has an optional API and a composite API, with slightly different lifecycle hooks

1. Lifecycle hooks for optional apis

The original Vue2 lifecycle hooks beforeDestroy and Destroyed have been renamed to beforeUnmount and unmounted respectively, so the corresponding event names need to be updated as well.

Summary of Vue3’s optional API lifecycle hooks based on the lifecycle diagram above:

  • beforeCreate: called synchronously after instance initialization but before data listening and event/listener configuration
  • created: is called immediately after the instance is created
  • beforeMount: is called before the mount begins
  • mounted: is called after the instance has been mounted
  • beforeUpdateDOM is called after data changes and before the DOM is updated
  • updated: is called after the virtual DOM has been re-rendered and updated due to data changes
  • beforeUnmount(In Vue2 it is:beforeDestroy) : called before the component instance is unloaded
  • unmounted(In Vue2 it is:destroyed) : called after the component instance is uninstalled

2. Lifecycle hooks for composite apis

The lifecycle hooks on the composite API have the same name as the optional API, but are prefixed withon: that is,mountedIt’s gonna look likeonMounted, please see the figure below for specific comparison

As you can see above, the beforeCreate and Create functions are missing from the lifecycle hooks called by setup(). Official explanation: Because setup runs around beforeCreate and Created lifecycle hooks, you don’t need to explicitly define them. In other words, any code written in these hooks should be written directly in the Setup function.

Code demo

Next, through a simple chestnut, to demonstrate the Vue3 lifecycle execution process

First we create three elements on the page. The page effect and HTML code look like this:

<template>
  <div class="count">
    <! Use v-if to show how to unload page elements -->
    <div v-if="isShow"> 
      <el-tag :key="count">Quantity display: {{count}}</el-tag>
      <el-button type="primary" size="small" @click="count++">Add 1</el-button>
    </div>
    <el-button type="danger" size="small" @click="isShow = false"
      >Uninstall < / el - button ></div>
</template> 

/ /... The CSS code is not important, so I'll just omit it here
Copy the code

Small problem:

  • Because this case uses itelemen-plusAnd in the use ofelement-plustagComponent is found when clicked“+ 1”Button not triggeredbeforeUpdateupdatedThese two lifecycle hooks.
  • The reason is that<el-tag>vueDom is not refreshed because of reuse. The solution: give<el-tag>Add a dynamickeyCan.
  • So the above code is used directlycountAs a dynamickeyValue. That is<el-tag :key="count">

Chestnut 1

A demo of lifecycle hooks using the optional API:

<script>
import { ref } from "vue";
export default {
  name: "Count".setup() {
    let count = ref(0);
    let isShow = ref(true);

    return { count, isShow };
  },

  // Lifecycle hooks for optional apis
  beforeCreate() {
    console.log("BeforeCreate calls");
  },
  created() {
    console.log("Created call");
  },
  beforeMount() {
    console.log("BeforeMount calls");
  },
  mounted() {
    console.log("Mounted calls");
  },
  beforeUpdate() {
    console.log("BeforeUpdate calls");
  },
  updated() {
    console.log("The updated call");
  },
  beforeUnmount() {
    console.log("BeforeUnmount calls");
  },
  unmounted() {
    console.log("Unmounted calls"); }}; </script>Copy the code
  1. When we opened the page, we found that when we entered the page, the four lifecycle hooks were called before and after creation and before and after mount

  1. When we click the page button “add 1”, the number displayed changes, triggeringbeforeUpdateupdatedThese two lifecycle hooks

  1. Click the “uninstall” button to triggerbeforeUnmountandunmountedThese two lifecycle hooks

Chestnut 2

A demonstration of lifecycle hooks using the composite API:

Before using the composite API’s lifecycle hooks, we import them through import

<script setup lang="ts">
import { ref, onMounted, defineProps, onBeforeMount, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from "vue";

let count = ref(0);
let isShow = ref(true);

// Lifecycle hooks for composite apis
onBeforeMount(() = > {
  console.log("OnBeforeMount starts calling");
});

onMounted(() = > {
  console.log("OnMounted starts calling");
});

onBeforeUpdate(() = > {
  console.log("OnBeforeUpdate start calling");
});

onUpdated(() = > {
  console.log("OnUpdated start call");
});

onBeforeUnmount(() = > {
  console.log("OnBeforeUnmount start call");
});

onUnmounted(() = > {
  console.log("OnUnmounted starts calling");
});
</script>
Copy the code
  1. Enter the page and callonBeforeMountonMountedThese two lifecycle hooks

  1. Click “plus 1” button, trigger data change, callonBeforeUpdateandonUpdatedThese two lifecycle hooks

3. Click “Uninstall” button to triggeronBeforeUnmountandonUnmountedThese two lifecycle hooks

conclusion

Well, Vue3 life cycle learning record here, there is insufficient hope that we can rationally correct, songhua will be very grateful to you. Today is the 31st, everyone should be preparing for the Reunion dinner, ha ha, I hope you have a happy Chinese New Year ~❤