Detailed explanation and classic interview questions of Vue life cycle and hook functions

Detailed explanation and classic interview questions of Vue life cycle and hook functions

1. Vue life cycle

The entire process from creation to destruction of a component is the life cycle

The process from creation to destruction of a Vue instance is the life cycle. That is, a series of processes from creation, initialization of data, compilation of templates, mounting Dom→rendering, updating→rendering, uninstallation, etc., we call this the life cycle of Vue.

2. Hook function

The Vue framework has built-in functions that automatically execute at specific times and perform specific operations as the component's life cycle phase progresses.

2.1 Divided into 4 stages and 8 methods:

stage Method Name Method Name
initialization beforeCreated created
Mount beforeMount Mounted
renew beforeUpdate updated
destroy beforeDestroy destroyed

The following diagram shows the life cycle of an instance:

2.2 Initialization Phase

1.new Vue() – Vue instantiation (the component is also a small Vue instance)

2.Init Events & Lifecycle – Initialization events and lifecycle functions

3.beforeCreate – lifecycle hook function is executed

4.Init injections & reactivity – Add data and methods inside Vue

5.created – lifecycle hook function is executed, instance is created

6. Next is the template compilation phase – start analysis

7.Has el option? – Is there an el option? – Check where to hang

No. Call $mount() method

Yes, continue to check the template option

<script>
export default {
    data(){
        return {
            msg: "hello, Vue"
        }
    },
    // 1. Initialization // After new Vue(), vue adds some properties and methods to the instance object, data and methods are initialized "before"
    beforeCreate(){
        console.log("beforeCreate -- execute");
        console.log(this.msg); // undefined
    },
    // After data and methods are initialized // Scenario: network request, register global event created(){
        console.log("created -- executed");
        console.log(this.msg); // hello, Vue
 
        this.timer = setInterval(() => {
            console.log("Hahaha");
        }, 1000)
    }
}
</script>

2.3 Mounting Phase

1. Template option check

Yes - compile template and return render function

None – compile the el option corresponding tag as template (template to be rendered)

2. Before the virtual DOM is mounted as the real DOM

3. beforeMount – lifecycle hook function is executed

4.Create … – attach the virtual DOM and rendered data to the real DOM

5. The real DOM is mounted

6.mounted – lifecycle hook function is executed

<template>
  <div>
      <p>Learning life cycle - see console printing</p>
      <p id="myP">{{ msg }}</p>
  </div>
</template>
 
<script>
export default {
    // ...Omit other codes// 2. Mounting// Before real DOM mounting// Scenario: Preprocess data, will not trigger the updated hook function beforeMount(){
        console.log("beforeMount -- Execution");
        console.log(document.getElementById("myP")); // null
 
        this.msg = "Revalue"
    },
    // After the real DOM is mounted // Scenario: Real DOM after mounting
    mounted(){
        console.log("mounted -- executed");
        console.log(document.getElementById("myP")); // p
    }
}
</script>

2.4 Update Phase

1. When the data in data changes, before updating DOM

2.beforeUpdate – lifecycle hook function is executed

3. Virtual DOM… – Virtual DOM re-rendering, patching to real DOM

4.updated – lifecycle hook function is executed

5. When data changes – repeat the cycle

<template>
  <div>
      <p>Learning life cycle - see console printing</p>
      <p id="myP">{{ msg }}</p>
      <ul id="myUL">
          <li v-for="(val, index) in arr" :key="index">
              {{ val }}
          </li>
      </ul>
      <button @click="arr.push(1000)">Click at the end to add value</button>
  </div>
</template>
 
<script>
export default {
    data(){
        return {
            msg: "hello, Vue",
            arr: [5, 8, 2, 1]
        }
    },
  
    // 3. Update // Prerequisite: execute only when data changes // Before update beforeUpdate(){
        console.log("beforeUpdate -- execute");
        console.log(document.querySelectorAll("#myUL>li")[4]); // undefined
    },
    // After updating // Scenario: Get the updated real DOM
    updated(){
        console.log("updated -- executed");
        console.log(document.querySelectorAll("#myUL>li")[4]); // li
    }
}
</script>

2.5 Destruction Phase

1. When $destroy() is called – for example, the component DOM is removed (e.g. v-if)

2. beforeDestroy – lifecycle hook function is executed

3. Disassemble data monitors, subcomponents, and event listeners

4. After the instance is destroyed, a hook function is finally triggered

5.destroyed – lifecycle hook function is executed

<script>
export default {
    // ...Other codes are omitted// 4. Destruction// Prerequisite: v-if="false" Destroy Vue instance// Scenario: Remove global events, remove current components, timers, timers, eventBus remove events $off method beforeDestroy(){
        // console.log('beforeDestroy -- executed');
        clearInterval(this.timer)
    },
    destroyed()
        // console.log("destroyed -- executed");
    }
}
</script>

at last:

Interview questions:

1.How many stages does the Vue life cycle consist of?

(1) beforeCreate

Called after instance initialization, but before data observer and event/watcher configuration.

(2) created

Called immediately after the instance is created. At this step, the instance has completed the following configurations: data observer, property and method operations, and watch/event callbacks. However, the mounting phase has not yet started and the $el property is not currently visible.

(3) beforeMount

Called before mounting starts: the associated render function is called for the first time.

(4) mounted

el is replaced by the newly created vm.$el and the hook is called after it is mounted on the instance. If the root instance mounts an in-document element, vm.$el will also be in-document when mounted is called.

(5) beforeUpdate

Called when data is updated, before the virtual DOM is patched. This is useful for accessing the existing DOM before updating it, such as manually removing added event listeners. This hook is not called during server-side rendering, as only the initial render happens on the server.

(6) updated

This hook is called after the virtual DOM is re-rendered and patched due to data changes.

(7) activated

Called when the keep-alive component is activated. This hook is not called during server-side rendering.

(8) deactivated

Called when the keep-alive component is deactivated. This hook is not called during server-side rendering.

(9) beforeDestroy

Called before the instance is destroyed. At this step, the instance is still fully usable. This hook is not called during server-side rendering.

(10) destroyed

Called after the Vue instance is destroyed. After the call, everything pointed to by the Vue instance will be unbound, all event listeners will be removed, and all child instances will be destroyed. This hook is not called during server-side rendering.

(11) errorCaptured (new in 2.5.0+)

Called when an error is caught from a descendant component. This hook receives three parameters: the error object, the component instance where the error occurred, and a string containing information about where the error originated. This hook can return false to stop the error from propagating further up.

2. Which hook functions will be triggered when the page is loaded for the first time?

beforeCreate, created, beforeMount, mounted these hook functions

Summarize

This is the end of this article about Vue life cycle and hook functions. For more relevant Vue life cycle and hook function content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to use the hook function of Vue instructions
  • Solve the problem of img not being loaded when VUE mounted hook function is executed, causing page layout
  • Detailed explanation of the execution order of various options and hook functions in Vue
  • The @click method of vue button is invalid and the hook function is not executed

<<:  Solution for multiple Docker containers not having the same port number

>>:  Data URI and MHTML complete solution for all browsers

Recommend

CSS3 achieves various border effects

Translucent border Result: Implementation code: &...

Nginx's practical method for solving cross-domain problems

Separate the front and back ends and use nginx to...

MySql 5.6.35 winx64 installation detailed tutorial

Note: There was no error in the project startup d...

Basic usage of custom directives in Vue

Table of contents Preface text 1. Global Registra...

Details of MutationObServer monitoring DOM elements in JavaScript

1. Basic Use It can be instantiated through the M...

Embed player in web page embed element autostart false invalid

Recently, I encountered the need to embed a player...

Summary of tips for setting the maximum number of connections in MySQL

Method 1: Command line modification We only need ...

jQuery custom magnifying glass effect

This article example shares the specific code of ...

HTML is the central foundation for the development of WEB standards

HTML-centric front-end development is almost what ...

Implementation of Linux command line wildcards and escape characters

If we want to perform batch operations on a type ...

CSS style writing order and naming conventions and precautions

The significance of writing order Reduce browser ...

Detailed tutorial on installing MySQL 8.0 from source code on CentOS 7.4

Table of contents 1. Environment 2. Preparation 3...

HTML tags: sub tag and sup tag

Today I will introduce two HTML tags that I don’t...

JavaScript canvas realizes dynamic point and line effect

This article shares the specific code for JavaScr...

How to limit the number of records in a table in MySQL

Table of contents 1. Trigger Solution 2. Partitio...