Home  >  Article  >  Web Front-end  >  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

PHPz
PHPzforward
2023-05-16 21:40:332216browse

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>App父级组件</h2>
  <button @click="childShow = !childShow">切换child子组件的显示</button>
  <hr />
  <child v-if="childShow" />
</template>
<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>
<style>
* {
  margin: 0;
  padding: 0;
}
</style>

Subcomponent child.vue

<template>
  <h3>child 子级组件</h3>
  <h4>{{ 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>

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>{{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>
(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部分同上代码,不多写了。

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

(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:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete