Table of Contents
The difference between the life cycle execution order in vue2 and vue3
Comparison of life cycle
App父级组件
Subcomponent child.vue
child 子级组件
{{ name }}
{{message}}
2、父子、兄弟组件的生命周期顺序
3、不同页面跳转时各页面生命周期的执行顺序
Home Web Front-end Vue.js What is the difference between the life cycle execution order in vue2 and vue3

What is the difference between the life cycle execution order in vue2 and vue3

May 16, 2023 pm 09:40 PM
vue3 vue2

The difference between the life cycle execution order in vue2 and vue3

Comparison of life cycle

  • The execution order in vue2beforeCreate=> created=>beforeMount =>mounted=>beforeUpdate =>updated=> beforeDestroy=>destroyed

  • execution sequence in vue3setup=>onBeforeMount=> onMounted=>onBeforeUpdate=>onUpdated=>onBeforeUnmount=>onUnmounted

Correspondence

vue2->vue3

  • ##beforeCreate ->setup

  • created -> setup

  • beforeMount -> onBeforeMount

  • ##mounted

    -> onMounted

  • beforeUpdate

    -> onBeforeUpdate

  • ##updated
  • -> ;

    onUpdated

    ##beforeDestroy
  • ->
  • onBeforeUnmount

    destroyed
  • ->
  • onUnmounted

    The setup in vue3 is equivalent to beforeCreate and created in vue2, but the execution is before beforeCreate and created, so Setup cannot use the data and methods in data and methods, that is, it cannot operate this. This in setup is equal to undefined, and because the variables and methods created in setup are eventually returned through return, the program in setup can only be synchronized. , and cannot be asynchronous, unless the return only accepts an asynchronous object, the object returns the variables and methods defined in the setup, and then the parent component uses the Suspense tag to wrap the asynchronous component;

  • If you want to use vue2's beforeDestroy in vue3 and destroyed need to change the names to beforeUnmount, unmounted respectively

If the vue2 writing method is also used in vue3, the vue3 writing method will be executed first;

Simple example explanation

Parent Component App.vue

<template>
  <h2 id="App父级组件">App父级组件</h2>
  <button @click="childShow = !childShow">切换child子组件的显示</button>
  <hr />
  <child v-if="childShow" />
</template>
Copy after login
<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
//引入子组件
import child from "./components/child.vue";
export default defineComponent({
  name: "App",
  components: {
    child,
  },
  setup() {
    const childShow = ref(true);
    return {
      childShow,
    };
  },
});
</script>
Copy after login
<style>
* {
  margin: 0;
  padding: 0;
}
</style>
Copy after login

Subcomponent child.vue

<template>
  <h3 id="child-nbsp-子级组件">child 子级组件</h3>
  <h4 id="nbsp-name-nbsp">{{ name }}</h4>
  <button @click="updateName">更新name</button>
</template>
<script lang="ts">
import {
  defineComponent,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
  ref,
} from "vue";
export default defineComponent({
  name: "child",
  //vue2中的生命周期钩子
  beforeCreate() {
    console.log("vue2 中的生命周期 beforeCreate");
  },
  created() {
    console.log("vue2 中的生命周期 created");
  },
  beforeMount() {
    console.log("vue2 中的生命周期 beforeMount");
  },
  mounted() {
    console.log("vue2 中的生命周期 mounted");
  },
  beforeUpdate() {
    console.log("vue2 中的生命周期 beforeUpdate");
  },
  updated() {
    console.log("vue2 中的生命周期 updated");
  },
  // vue2中的 beforeDestroy与 destroyed已经改名 无法使用
  beforeUnmount() {
    console.log("vue2 中的生命周期 beforeDestroy(beforeUnmount)");
  },
  unmounted() {
    console.log("vue2 中的生命周期 destroyed(unmounted)");
  },
  setup() {
    console.log("vue3中的setup");
    const name = ref("hhh");
    const updateName = () => {
      name.value += "6……6………6";
    };
    onBeforeMount(() => {
      console.log("vue3 中的生命周期 onBeforeMount");
    });
    onMounted(() => {
      console.log("vue3 中的生命周期 onMounted");
    });
    onBeforeUpdate(() => {
      console.log("vue3 中的生命周期 onBeforeUpdate");
    });
    onUpdated(() => {
      console.log("vue3 中的生命周期 onUpdated");
    });
    onBeforeUnmount(() => {
      console.log("vue3 中的生命周期 onBeforeUnmount");
    });
    onUnmounted(() => {
      console.log("vue3 中的生命周期 onUnmounted");
    });
    return {
      name,
      updateName,
    };
  },
});
</script>
Copy after login

The display effect when running

Enter the page and press f12 to open debugging refresh Page

What is the difference between the life cycle execution order in vue2 and vue3

It can be seen that What is the difference between the life cycle execution order in vue2 and vue3

setup
    in vue3 is executed between beforeCreate and created in front;
  • onBeforeMount
  • is executed in front of beforeMount;
  • ##onMounted

    is executed in front of mounted ;
  • Click to update name

You can see that

What is the difference between the life cycle execution order in vue2 and vue3

## in vue3

#onBeforeUpdate is executed in front of beforeUpdate;

  • onUpdated is executed in front of updated;

  • Click to switch the display of the child subcomponent

  • You can see that

What is the difference between the life cycle execution order in vue2 and vue3

in vue3

onBeforeUnmount is executed in front of beforeDestroy;

  • onUnmounted is executed in front of destroyed;

  • Life cycle execution sequence in three casesLife cycle: When creating a vue instance, it will go through a series of initialization processes (the process from creation to destruction of the Vue instance). This process is the life of vue. cycle.

  • Vue provides a series of callback functions to developers to facilitate us to add custom logic. The life cycle of Vue is from creation to destruction, and important node mounting data updates.

Create phase beforeCreate, created

    Mount the rendering page phase beforeMount, mounted
  • Update Stages beforeUpdate, updated
  • Uninstallation stage beforeDestory, destroyed
  • 1, single page life cycle sequence
  • present a wave Code, look at the execution sequence of each cycle hook function:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    	<meta charset="UTF-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<meta http-equiv="X-UA-Compatible" content="ie=edge">
    	<title>vue生命周期学习</title>
    	<script src="https://cdn.bootcss.com/vue/2.4.2/vue.js"></script>
    </head>
    <body>
    <div id="app">
    	<h2 id="message">{{message}}</h2>
    </div>
    </body>
    <script>
        var vm = new Vue({
            el: &#39;#app&#39;,
            data: {
                message: &#39;Vue的生命周期&#39;
            },
            beforeCreate: function() {
                console.group(&#39;------beforeCreate创建前状态------&#39;);
                console.log("%c%s", "color:red" , "el     : " + this.$el); //undefined
                console.log("%c%s", "color:red","data   : " + this.$data); //undefined
                console.log("%c%s", "color:red","message: " + this.message)
            },
            created: function() {
                console.group(&#39;------created创建完毕状态------&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el); //undefined
                console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
                console.log("%c%s", "color:red","message: " + this.message); //已被初始化
            },
            beforeMount: function() {
                console.group(&#39;------beforeMount挂载前状态------&#39;);
                console.log("%c%s", "color:red","el     : " + (this.$el)); //已被初始化
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
                console.log("%c%s", "color:red","message: " + this.message); //已被初始化
            },
            mounted: function() {
                console.group(&#39;------mounted 挂载结束状态------&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el); //已被初始化
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data); //已被初始化
                console.log("%c%s", "color:red","message: " + this.message); //已被初始化
            },
            beforeUpdate: function () {
                console.group(&#39;beforeUpdate 更新前状态===============》&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el.innerHTML);
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data);
                console.log("%c%s", "color:red","message: " + this.message);
            },
            updated: function () {
                console.group(&#39;updated 更新完成状态===============》&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el.innerHTML);
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data);
                console.log("%c%s", "color:red","message: " + this.message);
            },
            beforeDestroy: function () {
                console.group(&#39;beforeDestroy 销毁前状态===============》&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el);
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data);
                console.log("%c%s", "color:red","message: " + this.message);
            },
            destroyed: function () {
                console.group(&#39;destroyed 销毁完成状态===============》&#39;);
                console.log("%c%s", "color:red","el     : " + this.$el);
                console.log(this.$el);
                console.log("%c%s", "color:red","data   : " + this.$data);
                console.log("%c%s", "color:red","message: " + this.message)
            }
        })
    </script>
    </html>
    Copy after login
(1) Creation phase: initialize events and observe data

new Vue({}) creates an empty instance object. This object only has life cycle functions and some default events.

    In beforeCreate, neither $el nor data are initialized
  • created execution, completes the initialization of data, converts the template into a rendering function (render) through compilation, and executes the rendering function to obtain a virtual node tree (in memory)
  • 如果有模板文件,则编译成渲染函数;如果没有,则使用外部 HTML 作为模板进行渲染。综合排名优先级:render函数选项 > template选项 > outer HTML.

What is the difference between the life cycle execution order in vue2 and vue3

(2)挂载阶段

  • 为vue实例添加$el成员,替换挂载的DOM成员

  • 其中在beforeMount时,初始化el和data,但el和data,但el和data,但el还是使用{{message}}进行占位

  • mounted执行时,将message的值进行渲染

What is the difference between the life cycle execution order in vue2 and vue3

(3)更新阶段:触发对应组件的重新渲染

  • data 被改变时触发生命周期函数 beforeUpdate 执行,data是最新的,页面还未更新(旧的页面)

  • 根据最新的 data 重新渲染虚拟 DOM,并挂载到页面上,完成 Model 到 View 的更新

  • updated 执行,此时 data 和页面都是最新的

What is the difference between the life cycle execution order in vue2 and vue3

(4)销毁阶段

  • beforeDestroy钩子函数在实例销毁之前调用。在这一步,实例仍然完全可用。

  • destroyed钩子函数在Vue 实例销毁后调用。一旦调用,Vue 实例所绑定的所有内容都将被解绑,包括事件监听器,同时所有子实例都将被销毁。

2、父子、兄弟组件的生命周期顺序

<template>
	<div class="father">
		<component-A class="son_A"></component-A>
		<component-B class="son_B"></component-B>
	</div>
</template>
// script部分同上代码,不多写了。
Copy after login

主要可以从以下几种情况分析:

(1)创建过程:

父beforeCreate->父created->父beforeMount->子beforeCreate->子created->子beforeMount->子mounted->父mounted

What is the difference between the life cycle execution order in vue2 and vue3

(2)组件的内部更新:

What is the difference between the life cycle execution order in vue2 and vue3

子组件的内部更新过程是:子beforeUpdate->子updated

同理父组件的内部更新过程也是:父beforeUpdate->父updated

(3)组件之间的更新:

当子组件使用emit修改父组件状态时,刚好这个状态又绑定在子组件的props上,更新过程是:父beforeUpdate->子beforeUpdate->子updated->父updated

What is the difference between the life cycle execution order in vue2 and vue3 

(4)父子组件销毁:

父组件被销毁时子组件也同时被销毁,销毁的钩子过程是:父beforeDestroy->子beforeDestroy->子destroyed->父destroyed

What is the difference between the life cycle execution order in vue2 and vue3

父子组件完整的生命周期图如下所示:

What is the difference between the life cycle execution order in vue2 and vue3

  • 从上图可以看出,在父兄子组件挂载前,各组件的实例已经初始化完成。

  • 子组件挂载完成后,父组件还未挂载。因此,在父组件的mounted钩子中获取API数据时,子组件的mounted钩子无法获取到该数据。

  • 仔细看看父子组件生命周期钩子的执行顺序,会发现created这个钩子是按照从外内顺序执行,所以回显场景的解决方案是:在created中发起请求获取数据,依次在子组件的created中会接收到这个数据。

  • 无论嵌套多少层,Vue父子组件的生命周期钩子执行顺序都是从外到内再从内到外。

3、不同页面跳转时各页面生命周期的执行顺序

跳转不同页面和part2是相同的原理,从第一个页面(index)跳转到下一个页面(secondIndex)时,回先初始化secondIndex,之后在执行index页面的销毁阶段,最后secondIndex挂载完成.

What is the difference between the life cycle execution order in vue2 and vue3

What is the difference between the life cycle execution order in vue2 and vue3

The above is the detailed content of What is the difference between the life cycle execution order in vue2 and vue3. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

vue3+vite: How to solve the error when using require to dynamically import images in src vue3+vite: How to solve the error when using require to dynamically import images in src May 21, 2023 pm 03:16 PM

vue3+vite:src uses require to dynamically import images and error reports and solutions. vue3+vite dynamically imports multiple images. If vue3 is using typescript development, require will introduce image errors. requireisnotdefined cannot be used like vue2 such as imgUrl:require(' .../assets/test.png') is imported because typescript does not support require, so import is used. Here is how to solve it: use awaitimport

How to use tinymce in vue3 project How to use tinymce in vue3 project May 19, 2023 pm 08:40 PM

tinymce is a fully functional rich text editor plug-in, but introducing tinymce into vue is not as smooth as other Vue rich text plug-ins. tinymce itself is not suitable for Vue, and @tinymce/tinymce-vue needs to be introduced, and It is a foreign rich text plug-in and has not passed the Chinese version. You need to download the translation package from its official website (you may need to bypass the firewall). 1. Install related dependencies npminstalltinymce-Snpminstall@tinymce/tinymce-vue-S2. Download the Chinese package 3. Introduce the skin and Chinese package. Create a new tinymce folder in the project public folder and download the

How to refresh partial content of the page in Vue3 How to refresh partial content of the page in Vue3 May 26, 2023 pm 05:31 PM

To achieve partial refresh of the page, we only need to implement the re-rendering of the local component (dom). In Vue, the easiest way to achieve this effect is to use the v-if directive. In Vue2, in addition to using the v-if instruction to re-render the local dom, we can also create a new blank component. When we need to refresh the local page, jump to this blank component page, and then jump back in the beforeRouteEnter guard in the blank component. original page. As shown in the figure below, how to click the refresh button in Vue3.X to reload the DOM within the red box and display the corresponding loading status. Since the guard in the component in the scriptsetup syntax in Vue3.X only has o

How Vue3 parses markdown and implements code highlighting How Vue3 parses markdown and implements code highlighting May 20, 2023 pm 04:16 PM

Vue implements the blog front-end and needs to implement markdown parsing. If there is code, it needs to implement code highlighting. There are many markdown parsing libraries for Vue, such as markdown-it, vue-markdown-loader, marked, vue-markdown, etc. These libraries are all very similar. Marked is used here, and highlight.js is used as the code highlighting library. The specific implementation steps are as follows: 1. Install dependent libraries. Open the command window under the vue project and enter the following command npminstallmarked-save//marked to convert markdown into htmlnpmins

How to solve the problem that after the vue3 project is packaged and published to the server, the access page displays blank How to solve the problem that after the vue3 project is packaged and published to the server, the access page displays blank May 17, 2023 am 08:19 AM

After the vue3 project is packaged and published to the server, the access page displays blank 1. The publicPath in the vue.config.js file is processed as follows: const{defineConfig}=require('@vue/cli-service') module.exports=defineConfig({publicPath :process.env.NODE_ENV==='production'?'./':'/&

How to select an avatar and crop it in Vue3 How to select an avatar and crop it in Vue3 May 29, 2023 am 10:22 AM

The final effect is to install the VueCropper component yarnaddvue-cropper@next. The above installation value is for Vue3. If it is Vue2 or you want to use other methods to reference, please visit its official npm address: official tutorial. It is also very simple to reference and use it in a component. You only need to introduce the corresponding component and its style file. I do not reference it globally here, but only introduce import{userInfoByRequest}from'../js/api' in my component file. import{VueCropper}from'vue-cropper&

How to use vue3+ts+axios+pinia to achieve senseless refresh How to use vue3+ts+axios+pinia to achieve senseless refresh May 25, 2023 pm 03:37 PM

vue3+ts+axios+pinia realizes senseless refresh 1. First download aiXos and pinianpmipinia in the project--savenpminstallaxios--save2. Encapsulate axios request-----Download js-cookienpmiJS-cookie-s//Introduce aixosimporttype{AxiosRequestConfig ,AxiosResponse}from"axios";importaxiosfrom'axios';import{ElMess

How to use Vue3 reusable components How to use Vue3 reusable components May 20, 2023 pm 07:25 PM

Preface Whether it is vue or react, when we encounter multiple repeated codes, we will think about how to reuse these codes instead of filling a file with a bunch of redundant codes. In fact, both vue and react can achieve reuse by extracting components, but if you encounter some small code fragments and you don’t want to extract another file, in comparison, react can be used in the same Declare the corresponding widget in the file, or implement it through renderfunction, such as: constDemo:FC=({msg})=>{returndemomsgis{msg}}constApp:FC=()=>{return(

See all articles