Man is born free, but he is everywhere in chains. He thinks he is the master of all others, but he is a slave to all others. -- -- RousseauCopy the code
Life cycle diagram
Lifecycle hook description
BeforeCreate (before initialization bounds)
After instance initialization, data Observer and Event/Watcher events are called before configuration.
Data and $el are not initialized; both are undefined
Created (after initializing the interface)
Called after the instance has been created. In this step, the instance completes the configuration of data Observer, property and method operations, and Watch/Event event callbacks. However, the mount phase has not yet started and the $EL attribute is not currently visible. DOM manipulation at this stage must be done in the vue.nexttick () callback.
Data is initialized, but $el is not
I think the point is that the mount phase has not started yet, which means that the template has not been rendered to HTML, so looking up page elements by id or whatever is not guaranteed to be found. Therefore, creadted hook functions are generally used to initialize data.
BeforeMount (before rendering DOM)
Called before the mount begins: The associated render function is called for the first time.
Eg:
{{message}}
Mounted (after rendering DOM)
El is replaced by the newly created vm.$el, which is called after being mounted to the instance. DOM operations are usually performed in mounted hook functions.
Data and $el already exist, and DOM load is complete, complete mount
BeforeCreate, Created, beforeMount, and Mounted are triggered by the first page load.
BeforeUpdate (Before updating data)
Called when data is updated, before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional re-rendering, which is a last chance to modify the data before re-rendering.
Updated (after data is updated)
This hook is called after the virtual DOM 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 DOM-dependent operations.
You should avoid changing the state during this time, as this may result in an update infinite loop where the hook is not called during server-side rendering
BeforeDestroy (Before uninstalling components)
Called before instance destruction. At this step, the instance is still fully available.
Destroyed (after updating data)
Called after the Vue instance is destroyed. When called, everything indicated by the Vue instance is unbound, all event listeners are removed, and all subinstances are destroyed. This hook is not called during server-side rendering.
In addition, keep-alive has the unique lifecycle of activated and deactivated, respectively. Components wrapped with keep-alive are not destroyed during switchover. Instead, they are cached in memory and the deactivated hook function is executed. After a cache rendering is hit, the Activated hook function is executed.
Lifecycle hook usage scenarios
- beforeCreate
- You can add some loading effects at this point and remove them at created
- created
- Methods that require asynchronous requests for data can be executed at this point, completing the initialization of the data
- beforeMount
- Before mounting, although you don’t have a specific DOM element, the root node that vue mounts is created and you can continue to do some operations around that root element
- mounted
- This is where you make a back-end request, get your data back, and do something with the routing hook
- beforeUpdate
- You can access the existing DOM before updating, for example by manually removing the added event listener
- updated
- This parameter is used when data update requires unified service processing
- beforeDestroy
- You can do some deletion prompts, such as: are you sure to delete XX?
- destroyed
- Destroy the listener event. The component is gone and cannot manipulate anything inside it
As you can see above, asynchronous requests can be executed in both created cycles and beforeMount and Mounted cycles because data is already created in these hook functions and can be assigned to the data returned by the server side.
Since asynchronous functions do not block the entire VUE lifecycle, requests can be made at any stage. If you want the user to feel that the page is loaded this morning and reduce the amount of blank page time, it is recommended to put it in the creation phase and then deal with null and undefined. After all, the earlier the data is retrieved, the more timely the mounted instance will be rendered. In addition, SSR(server rendering) does not support beforeMount and Mounted hook functions, so creating helps consistency.
The life cycle of parent and child components
- Execution order
- Parent component starts execution to beforeMount, then begins child component execution, and finally parent component Mounted cycle
- If there are siblings, the parent component starts to run beforeMount, then the siblings continue to run beforeMount, then mount in sequence, and finally the parent component mounts
- The parent component is mounted only after the child component is mounted
- The parent actively executes the beforeUpdated/updated hook function once when the child finishes mounting (first only)
- Parent and child components are monitored separately during data changes, but the data in the update props is associated
- When a parent component is destroyed, the child component is destroyed before the parent component is destroyed
- Before Mounted, sibling components are initialized separately and mounted from top to bottom
- When there is no data correlation, updates and destruction between sibling components are disconnected
Loading the rendering process
Vue’s parent and child component lifecycle hook function execution sequence can be categorized into the following four parts:
-
Parent beforeCreate -> Parent created -> parent beforeMount -> child beforeCreate -> child created -> child beforeMount -> Child Mounted -> parent Mounted
-
Child component update process Parent beforeUpdate -> child beforeUpdate -> Child updated -> Parent updated
-
Parent Component Update process Parent beforeUpdate -> Parent updated
-
Process parent beforeDestroy -> Child beforeDestroy -> Child destroyed -> Parent destroyed
The test code
- The Vue test file code is as follows:
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png" />
<p>{{message}}</p>
</div>
</template>
<script>
export default {
name: "app".data() {
return {
message: 1
};
},
beforeCreate() {
console.log("Called beforeCreate");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
created() {
console.log("Call created");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
beforeMount() {
console.log("Called beforeMount");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
mounted() {
console.log("Mounted");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
beforeUpdate() {
console.log("BeforeUpdate called");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
updated() {
console.log("Invoked updated");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
beforeDestory() {
console.log("Called beforeDestory");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --");
},
destoryed() {
console.log("Destoryed called");
console.log("message:",this.message);
console.log("$el:",this.$el);
console.log("-- -- -- -- -- -- -- -- -- -- -- --"); }}; </script>Copy the code
- The following output is displayed:
It can be seen that el is rendered within mounted cycles
Other Points for attention
Created (){} and Mounted (){} are both created(){} and mounted(){}. Mounted () is mounted to a DOM node.
Note that all lifecycle functions of Vue are automatically bound to the context of this. So, if you use the arrow function here, you get the parent scope that this points to, and you get an error.
Wrong form:
mounted:(a)= >{}Copy the code
References:
-
Detail the Vue lifecycle implementation
-
Vue life cycle details