Interviewer: What does Vue do in each lifecycle?

Get into the habit of writing together! This is the second day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

foreword

This is a very frequently asked interview question. Generally, if the interviewer is going to ask Vue-related questions, they often start with the Vue life cycle. Many small partners may think this question is very simple, so they often do not prepare, as a result, the answer is not comprehensive enough every time, and the interviewer will think that you have an improper attitude.

So, let's learn the basics! At least have the right attitude!

1. What is the life cycle of Vue?

If you use the Vue framework, learning its lifecycle is unavoidable. We live in old age, sickness and death, dust returns to dust, and earth returns to earth. This is a cycle. The same is true for a Vue application, from the initial creation to the final demise, which is also a cycle.

A person's life is divided into stages: childhood, adolescence, youth, middle age, and old age. We need to do different things at different stages. The same is true for a Vue application, except that it replaces the various stages of the life cycle with hook functions. Inside the hook function is what we need to do.

A picture on the official website very clearly introduces the life cycle of a Vue application or component:

This is a life cycle diagram of Vue2.x. From creation to destruction, it is divided into these stages: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestory, destroyed.

These are the hook functions corresponding to each stage, just like each stage of our life, then let's talk about what each hook function is doing.

2.beforeCreate

The first periodic function, it will be executed before the Vue instance is created. At this time, the data or methods in data and methods have not been initialized and cannot be called. Only some default events can be used.

Sample code:

<script>
export default {
  data() {
    return {
      msg: "小猪课堂",
    };
  },
  beforeCreate() {
    console.info("-----beforeCreate-----");
    console.info("data", this.msg);
    console.info("methods", this.getMsg);
  },
  methods: {
    getMsg() {
      return
    },
  },
};
</script>
复制代码

Output result:

In the previous code, we defined a data data and a method. As you can see, we can't get the data and methods in the beforeCreate hook function, because they have not been initialized at this time.

3.created

顾名思义,该钩子函数是在Vue实例化之后执行的,此时data和methods已经初始化完成了,可以供我们调用,但是模板还没有编译,也就是我们还不能获取到DOM。

实例代码:

created() {
  console.info("-----created-----");
  console.info("data", this.msg);
  console.info("methods", this.getMsg);
  console.info("el", this.$el);
},
复制代码

输出结果:

可以看到data和methods可以获取到了,但是el节点还不能获取,因为此时模板渲染还没有开始。

4.beforeMount

该钩子函数在模板渲染之前调用,也就是DOM节点挂载到真实DOM树之前调用。此模板进行编译,会调用render函数生成vDom,也就是虚拟DOM,此时我们同样无法获取DOM节点。

示例代码:

beforeMount(){
  console.info("-----beforeMount-----");
  console.info("el", this.$el);
},
复制代码

输出结果:

可以看到此时我们同样是无法获取DOM节点的,因为此时只存在VDOM,还在JS级别。

5.mounted

执行该钩子函数时,我们的模板编译好了,而且挂载到真实DOM树上面去了,也就是我们的页面可以显示了。

示例代码:

mounted(){
  console.info("-----mounted-----");
  console.info("el", this.$el);
},
复制代码

输出结果:

此时我们可以获取到DOM节点了。

6.beforeUpdate

上面的生命周期函数其实都发生在初始化阶段,当我们的页面或者组件发生变化时,便会执行对应的更新阶段的钩子函数。

该钩子函数在data数据发生变化之后调用,此时data里面的数据已经是最新的了,但是页面上DOM还没有更新最新的数据。

示例代码:

beforeUpdate() {
  console.info("-----beforeUpdate-----");
  console.info("data", this.msg);
},
methods: {
  getMsg() {
    return;
  },
  changeMsg() {
    this.msg = "更改后的小猪课堂";
  },
},
复制代码

输出结果:

上段代码中我们新增了一个改变data数据的方法,点击页面上的按钮便会更改数据,然后我们在beforeUpdate钩子函数后面打了一个断点。此时会发现控制台打印的msg和页面上的msg不一致,这也就印证beforeUpdate发生在data更新之后,DOM渲染之前。

7.updated

该钩子函数会在data数据更新之后执行,而且此时页面也渲染更新完成了,显示的就是最新的数据。

示例代码:

updated(){
  console.info("-----updated-----");
  console.info("data", this.msg);
},
methods: {
  getMsg() {
    return;
  },
  changeMsg() {
    this.msg = "更改后的小猪课堂";
  },
},
复制代码

输出结果:

上段代码基本和beforeUpdate代码一样,我们在updated钩子函数后面打了一个断点,当执行该钩子函数的时候,我们发现此时页面上的数据和我们data中的数据是一致的,说明此时data和页面都已经完成了更新。

注意:不要在updated中修改data数据,很容易造成死循环。

8.beforeDestroy

This hook function occurs before the Vue component instance is destroyed. At this time, the component has not actually been destroyed and can be used normally. We usually cancel some global or custom events in this hook function.

Sample code:

beforeDestory(){
  console.info("-----beforeDestory-----");
  console.info("组件销毁之前");
},
复制代码

9.destroyed

This hook function will be executed after the component instance is destroyed, at which time all components including subcomponents are destroyed.

Sample code:

destroyed(){
  console.info("-----destroyed-----");
  console.info("组件被销毁");
},
复制代码

Usually only the DOM shell is left at this point.

10. Supplement

Usually, when we switch routes and other operations, the components will be destroyed, and when they switch back, the components will be re-rendered. But sometimes in order to improve performance, we can switch routes without destroying components. At this time, we need to use keep-alive, a built-in component of Vue.

Components wrapped with keep-alive components will not be destroyed. After using keep-alive, we will have two more life cycle functions.

10.1 activated

Executed when the page is rendered.

Example code:

<keep-alive>
  <router-view />
</keep-alive>
activated(){
  console.log("home组件被渲染")
}
复制代码

Output result:

In the above code, we wrap the routing component with keep-alive. When we render the component for the first time, the mounted hook function of the component is executed, but when we keep switching routes, the mounted hook function is not executed. Only the activated hook function is executed, indicating that the component has not been destroyed.

10.2 deactivated

Executed when the page is hidden or when the page is about to be replaced with a new page.

Example code:

deactivated(){
  console.info("deactivated被执行")
}
复制代码

Output result:

When our component is about to be switched away, this hook function will be executed, which is similar to the beforeDestroy hook function, but the effect is completely different.

Summarize

The life cycle functions of Vue must be mastered. Many interviewers often feel that it is simple. They don’t study hard and focus on the project. As a result, the interview is incomplete and eventually eliminated. Everyone must pay attention to it.

If you think the article is not enjoyable, you can watch the video recorded by my station B: Pig Classroom

Guess you like

Origin juejin.im/post/7085706667987812360