[Front end] Vue life cycle function (detailed explanation + Chinese diagram)

1. What is the life cycle

1. Meaning

  • life cycle:The process from the creation of the vue instance to the time when the vue instance is ecstasy

2. Understand

  • vue instanceCreate and destroy processlikeHuman life from birth to death. What can we do during some of these major experiences , that is, at special points in time
  • In the life of vue, from the time period when the vue component is created until it is destroyed, several special ones are also establishedpoint in time, for the convenience of developers to implement thespecific timeLet vue at a specific timedo specific things. It is set by a method called "lifecycle hook function". In vue, the lifetime of vue is dominated by 8 life cycle hook functions.
  • It can also be understood as a callback function. When we write a periodic function, Vue will automatically execute this function at the specified time point

Hook function: It can be simply understood as a function that the system automatically executes at different stages without user intervention

2. Definition of life cycle (official website)

1、view2

Vue2 life cycle

2、view3

Vue3 life cycle

3. Diagram of life cycle

1. Vue2 life cycle diagram

insert image description here

2. Vue3 life cycle diagram

insert image description here

4. The life cycle of Vue

insert image description here

The main Vue lifecycle events are divided into two hooks, which are called before and after the event, and there are 4 main events (8 hooks) in the vue application

● Create – Execute when the component is created
● Mount – Execute when the DOM is mounted
Update – Execute when the response data is modified
Destroy – Execute immediately before the element is destroyed

Five, the difference between the Vue2 life cycle and the Vue3 life cycle

insert image description here

Six, the main stages of the Vue life cycle and 8 cycle functions

1、options API和composition API

In [options API], the lifecycle hook is an option exposed on the vue instance, we only need to call and use it.
In [composition API], we need to introduce the lifecycle hook into the project before it can be used

import { onBeforeMount, onMounted, onBeforeUpdate, onUpdated, onBeforeUnmount, onUnmounted } from 'vue'

insert image description here
In the combination API, use the setup() method to replace beforeCreate and created, then the methods in these two life cycles will be executed in setup()

2. Creation phase (initialization of related properties): beforeCreate(), created()

  • beforeCreate
  • Note : At this time, the data in data cannot be obtained, that is to saythis.$datagot isundefined
  • created

2. Stage before mounting: beforeMount(), onBeforeMount()

  1. Called before the component DOM is actually rendered. At this time, the root element is not yet. In the options API, you can use this.$data to access; in the composition API, you must use ref on the root element if you want to access
import { ref, onBeforeMount } from "vue";

  export default {
    setup() {
      console.log("setup,创建前后")
      const count = ref({
        str: '你好',
        number: 123
      })

      onBeforeMount(() => {
        console.log("onBeforeMount -- composition API", "挂载前",count.value.str)
      })

      return {
        count,
      }
    },

    data(){
      return{
        number: 123
      }
    },
    beforeMount() {
      console.log("beforeMount -- options API,挂载前",this.$data.number)
    },

insert image description here

3. Post-mount stage: mounted(), onMounted()

  1. mounted(), onMounted() [this is when the page is loaded]
  2. Note : By default, it will only be triggered once in the life cycle of the component
import { ref, onMounted } from "vue";

  export default {
    setup() {
      console.log("setup,创建前后")
      const count = ref({
        str: '你好',
        number: 123
      })

      onMounted(() => {
        console.log("onMounted -- composition API", "挂载前",count.value.str)
      })

      return {
        count,
      }
    },

    data(){
      return{
        number: 123
      }
    },
    mounted() {
      console.log("mounted -- options API,挂载前",this.$data.number)
    },

insert image description here

4. Update phase (element or component change operation): beforeUpdate(), updated(), onBeforeUpdate(), onUpdated()

  1. Called when the data is updated. After the DOM is updated, the updated() and onUpdated() methods will be called
  2. retriggerable
<template>
  <div>
    <h1>Hello World</h1>
    {
   
   { count.str }}
    <button @click="changeStr">修改str的按钮</button>
  </div>
  <hr />
  <div>
    <h1>Hello World</h1>
    {
   
   { this.$data.number }}
    <button @click="changeNumber">修改number的按钮</button>
  </div>
</template>

<script>
  import {
      
       ref, onBeforeUpdate, onUpdated } from "vue";

  export default {
      
      
    //Vue3写法
    setup() {
      
      
      console.log("setup,创建前后")
      const count = ref({
      
      
        str: '你好',
        number: 123
      })
      onBeforeUpdate(() => {
      
      
        console.log("onBeforeUpdate -- composition API", "更新前")
      })
      onUpdated(() => {
      
      
        console.log("onUpdated -- composition API", "更新后",count.value.str)
      })

      function changeStr() {
      
      
        count.value.str = "已修改"
      }

      return {
      
      
        count,
        changeStr
      }
    },

    //Vue2写法
    data(){
      
      
      return{
      
      
        number: 123
      }
    },
    methods: {
      
      
      changeNumber() {
      
      
        this.$data.number = 456
      }
    },

    beforeUpdate() {
      
      
      console.log("beforeUpdate -- options API,更新前")
    },
    updated() {
      
      
      console.log("updated -- options API,更新后",this.$data.number)
    },
  }
</script>

insert image description here

5. Destruction phase (destruction of related attributes): beforeUnmount() and onBeforeUnmounted(), unmounted() and onUnmounted()

When is it triggered? : close the page (not the browser)

<script>
import {
      
       ref, onBeforeUnmount, onUnmounted } from "vue";

export default {
      
      
    setup() {
      
      
        onBeforeUnmount(() => {
      
      
            console.log("onBeforeUnmount -- composition API", "销毁前")
        })
        onUnmounted(() => {
      
      
            console.log("onUnmounted -- composition API", "销毁后")
        })
    },


    beforeUnmount() {
      
      
        console.log("beforeUnmount -- options API,销毁前")
    },
    unmounted() {
      
      
        console.log("unmounted -- options API,销毁后")
    }
}
</script>

insert image description here

7. Interview questions

1. What are the life cycles of commonly used vue?

①. Main points

4 stages, 8 periodic functions

2. If there is a parent-child relationship between components, what is the order in which the life cycles of the parent component (A) and the child component (B) are executed?

①, train of thought

  • A component has 8 common cycles: create 2, mount 2, update 2, destroy 2
  • B component has 8 common cycles: create 2, mount 2, update 2, destroy 2

②, the answer

  • Divide 8 cycles into three phases (1-4, 5-6, 7-8)
  • Rendering stage: parent 1 → parent 2 → parent 3 → child 1 → child 2 → child 3 → child 4 → parent 4
  • Update phase: parent 5 → child 5 → child 6 → parent 6
  • Update phase: parent 5 → child 5 → child 6 → parent 6

Guess you like

Origin blog.csdn.net/weixin_45490023/article/details/132180830