Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The execution order and hook function of the life cycle of Vue parent and child components

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "Vue parent and son component life cycle execution order and hook function". In daily operation, I believe many people have doubts about the execution order and hook function of Vue parent and son component life cycle. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "Vue parent and son component life cycle execution sequence and hook function". Next, please follow the editor to study!

First attach a life cycle diagram of vue instances on the official website. Each Vue instance needs to go through a series of initialization processes when it is created, such as setting up data monitoring, compiling templates, mounting instances to DOM and updating DOM when data changes. At the same time, some functions called lifecycle hooks (callback functions) will be run during this process, which gives users the opportunity to add their own code at different stages.

1. Life cycle diagram of vue

Throughout the lifecycle of the vue instance, different hook functions are provided for us to perform different operations. First list the detailed analysis of each hook function on the vue official website.

Life cycle hook

Life cycle hook

Detailed beforeCreate is called after instance initialization and before data observation (data observer) and event/watcher events are configured. The created instance is called after it has been created. In this step, the instance has completed the following configuration: data observation (data observer), operation of properties and methods, and watch/event event callback. However, the mount phase has not yet begun, and the $el property is not currently visible. BeforeMount is called before the mount starts: the related render function is called for the first time. The hook is called after the mountedel is replaced by the newly created vm.$el and mounted to the instance. If the root instance mounts an element in the document, the vm.$el is also in the document when mounted is called. Called when beforeUpdate data is updated, before the virtual DOM is re-rendered and patched. You can change the state further in this hook, which will not trigger additional re-rendering. The hook is called after the virtual DOM of updated is re-rendered and patched due to data changes. When this hook is called, the component DOM has been updated, so you can now perform operations that depend on DOM. Called when the activatedkeep-alive component is activated. Called when the deactivatedkeep-alive component is deactivated. Called before the beforeDestroy instance is destroyed. At this step, the instance is still fully available. Called after the destroyedVue instance is terminated. After the call, everything indicated by the Vue instance is unbound, all event listeners are removed, and all child instances are also

Called after the instance is destroyed. After the call, everything indicated by the Vue instance is unbound, all event listeners are removed, and all child instances are destroyed.

2. Practical operation

Let's understand the lifecycle creation process of parent-child components and the real-time state changes of hook function execution during the actual code execution.

The test is based on the following code and can be executed after the vue.js file is introduced. (after opening the page, pressing Refresh again will automatically enter the debugger state.)

Document

{{message}}

Var child = {template: 'from child: {{childMsg}}', props: ['msg'], data: function () {return {childMsg:' child'}}, beforeCreate: function () {debugger;}, created: function () {debugger;}, beforeMount: function () {debugger }, mounted: function () {debugger;}, deactivated: function () {alert ("keepAlive deactivation");}, activated: function () {console.log ('component activated');}, beforeDestroy: function () {console.group (' beforeDestroy pre-destruction status = ") Var state = {'el': this.$el,' data': this.$data, 'message': this.message} console.log (this.$el); console.log (state);}, destroyed: function () {console.group (' destroyed destruction completion status = "') Var state = {'el': this.$el,' data': this.$data, 'message': this.message} console.log (this.$el); console.log (state);},} Var vm = new Vue ({el:'# app', data: {message: 'father', msg1: "hello", show: true}, beforeCreate: function () {debugger;}, created: function () {debugger;}, beforeMount: function () {debugger;}, mounted: function () {debugger }, beforeUpdate: function () {alert (before page view update);}, updated: function () {alert (after page view update);}, beforeDestroy: function () {console.group ('beforeDestroy pre-destruction status = ") Var state = {'el': this.$el,' data': this.$data, 'message': this.message} console.log (this.$el); console.log (state);}, destroyed: function () {console.group (' destroyed destruction completion status = "') Var state = {'el': this.$el,' data': this.$data, 'message': this.message} console.log (this.$el); console.log (state);}, components: {' my-components': child}})

3.1. Life cycle debugging

First, we create an instance of Vue, vm, and mount it to the element in the page whose id is "app".

3.1.1. BeforeCreate phase of the root component

As you can see, when the beforeCreate () function is called, only some necessary initialization operations are performed (such as some global configuration and some property initialization of the root instance). In this case, the data property is undefined and there is no data to manipulate.

3.1.2. Created phase of the root component

Call the Created () function, where the instance has completed the following configuration: data proxy and dynamic data binding (data observer), operation of properties and methods, and watch/event event callback. However, the mount phase has not yet begun, and the $el property is not currently visible.

3.1.3. BeforeMount phase of the root component

Before calling the boforeMount () function, it is first determined whether the object has an el option. Continue compiling down if any, and if there is no el option, stop compiling, which means stopping the life cycle until vm.$mount (el) is called on the vue instance

In this example, we have the el element, so the boforeMount () function is called, and the template parsing function has already started, but the $el element has not yet been mounted on the page, so the page view has not been updated. In the red, or {{message}}, here is the application of Virtual DOM (virtual Dom) technology, first occupied the pit. Render the values later when the mounted is mounted.

3.1.4. BeforeCreate, Created, beforeMount, Mounted phases of subcomponents

After the parent component executes the beforeMount phase, you enter the beforeCreate, Created, and beforeMount phases of the child component, which are similar to the parent component. After the beforeMount phase, the Mounted phase is executed, when the child component is mounted to the parent component, and the parent component is then mounted to the page.

As you can see from the following figure, after the beforeMount phase and before the Mounted phase, the data has been loaded on the view, that is, the view update is triggered when the $el element is mounted to the page.

3.1.5. Activated phase of sub-components

We found that it was triggered after all the child parent components were mounted to the page. This is because the subcomponent my-components is wrapped and triggered with the mount of $el. If the subcomponent is not wrapped, the phase will not be triggered.

3.1.6, mounted phase of the parent component

When mounted is executed: the el has been rendered and mounted to the instance.

At this point, the stage from initializing the Vue instance to mounting the new template on the page is complete, and exit debugger. Let's take a look at the deactivated, beforeUpdate, updated, beforeDestroy, destroyed hook functions.

3.2Phase of deactivated, beforeUpdate, updated

As can be seen from the lifecycle function, the beforeUpdate () function is triggered when the data changes and before the virtual DOM rendering renders the page again, and the view has not changed. The updated () function is triggered when the view of the virtual DOM rendered page is updated.

We might as well change vm.show = false. When we modify this property, not only the beforeUpdate and updated functions will be triggered, but the deactivated function will also be triggered (because it is called when the keep-alive component is deactivated). We might as well consider whether the deactivated function will be called after beforeUpdate or updated.

We enter vm.show = false in the console. The calling order of the three is beforeUpdate, deactivated and updated, respectively. What we can know is that the trigger time of the deactivated function is triggered when the view is updated. Because the keep-alive component is disabled only when the view is updated.

Life cycle between beforeDestroy and destroyed hook functions

Now we can destroy the Vue instance by calling the app.$destroy () method. The console test is as follows:

We found that the instance still exists, but at this time the change has taken place elsewhere.

The beforeDestroy hook function is called before the instance is destroyed. At this step, the instance is still fully available.

The destroyed hook function is called after the Vue instance is destroyed. After the call, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all child instances will be destroyed (that is, the subcomponent will trigger the corresponding function). Destruction here does not mean 'erase', but rather means' unbind'.

When destroyed, the beforeDestory function is passed from parent to child, and the destory is passed from child to parent.

4. Some ideas of applying hook functions can manipulate data data in created hooks. At this time, you can make an ajax request to assign the returned data to data.

Although the updated function will be triggered when the data changes, it can not accurately determine which attribute value has been changed, so in the actual situation, use the computed or match function to listen for the change of the attribute and do some other operations. The mounted dom is manipulated with the mounted hook, and the DOM has been rendered to the page. When using vue-router, it is sometimes necessary to cache the component state, so the created hook will not be called repeatedly. If our subcomponents need to do something each time the state is loaded or switched, we can use the activated hook to trigger. All lifecycle hooks automatically bind the this context to the instance, so you cannot use the arrow function to define a lifecycle method (for example, created: () = > this.fetchTodos ()). This causes the this to point to the parent.

5. Summary

Load render passes

Father beforeCreate- > father created- > father beforeMount- > son beforeCreate- > son created- > son beforeMount- > son mounted- > father mounted

Subcomponent update process

Parent beforeUpdate- > Child beforeUpdate-> Child updated- > parent updated

Parent component update process

Parent beforeUpdate- > parent updated

Destruction process

Parent beforeDestroy- > Child beforeDestroy-> Child destroyed- > parent destroyed

At this point, the study on the execution order and hook functions of the life cycle of Vue parent and child components is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report