Life cycle Hooks

Source: Internet
Author: User
Tags event listener

All lifecycle hooks automatically bind this The context to the instance, so you can access the data and operate on the properties and methods. This means that you cannot use the arrow functions to define a life cycle method ( created: () => this.fetchTodos() for example). This is because the arrow functions are bound to the parent this context, so unlike the Vue instance you this.fetchTodos expect, the behavior is undefined.

First, create a sample test hook function
<! DOCTYPE html>varTest = {//test the hook function in the test componentdata () {return{msg:"Ah haha"}}, Template: '<div> <div>{{msg}}</div> <button @click = "Changehandler" > Modify &L T;/button> </div>', methods:{Changehandler () { This. msg = This. msg + ' Alex '; }}, Beforecreate () {//called before the current component is createdConsole.log ( This. msg);//output undefined, indicating that the current data is empty}, created () {//called after the current component is created                //using this component will trigger the above hook function, created can manipulate the data, send Ajax,                //and can realize the impact of Vue on the page, the application is mainly: Send AJAX requestsConsole.log ( This. msg);//console output "ah haha"                //this.msg= "hehe hey";}, Beforemount () {//the data is called before it is loaded into the DOMConsole.log (document.getElementById (' app '))); }, mounted () {//after loading the data into the DOM, it calls                //This place can manipulate the DOM .                //can get to the real DOM element, the DOM after the Vue operationConsole.log (document.getElementById (' app '))); }, BeforeUpdate () {//before the update, call this hook, apply: Get the original DomConsole.log (document.getElementById (' app '). InnerHTML);//Get all elements}, Updated () {//after the update, call this hook to apply: Get the latest DomConsole.log (document.getElementById (' app '). InnerHTML);//Get all elements}, Beforedestroy () {Console.log (' Beforedestroy '); }, destroyed () {Console.log (' Destroyed '); }, activated () {Console.log (' The component is activated '); }, deactivated () {Console.log (' The component is deactivated ');        }        }; varAPP ={data () {return{isshow:true}}, Template: '<div> <keep-alive> <test Vif= "Isshow" ></Test> </keep-alive> <button @click = "Changehandler" > Changing components of life </button> death </div>', methods:{Changehandler () { This. Isshow =! This. Isshow; }}, components:{//Mount Test ComponentTest}}; //Create Destroy        NewVue ({el:' #app ', Template: ", components:{App}}); </script></body>View Code

Two, each hook function introduction 1, beforecreate and created

  beforecreate: After the instance is initialized, the data observer and the Event/watcher event configuration are called.

  created: called immediately after the instance creation is complete. In this step, the instance has completed the following configuration: Data Observer, properties and method operations, Watch/event event callbacks. However, the Mount phase has not yet started $el and the properties are not currently visible.

Template: '    <div>        {msg}}    </div> ', Beforecreate () {   ////Console.log before the current component is created    ( THIS.MSG);   Output undefined, which indicates that the current data is empty},created () {        ////After the current component has been created, it    will trigger the above hook function, created can manipulate data, send Ajax,    // And can realize the impact of Vue on the page, the application is mainly: Send Ajax request    Console.log (this.msg);  Console output "Ah haha"    this.msg= "hehe Hey";},

The display effect is as follows:

  

2, Beforemount and mounted

  beforemount: called before the mount starts: the related function is called render for the first time. The hook is not called during server-side rendering.

  mounted: el The hook is called vm.$el after a newly created replacement is mounted to the instance. If the root instance mounts a document element, mounted It is vm.$el also within the document when it is invoked. The hook is not called during server-side rendering.

Template: '    <div>        {msg}}    </div> ', Beforemount () {   ////Load data to DOM before calling    Console.log (document.getElementById (' app '));},mounted () {   //Loading data into the DOM will be called//    This place can manipulate the DOM    //can get to the real DOM element, After the Vue Operation Dom    Console.log (document.getElementById (' app '));},

The display results are as follows:

  

3, BeforeUpdate and updated

  beforeUpdate: Called when data is updated, which occurs before the virtual DOM is patched . This is a good place to access existing DOM before updating, such as manually removing an event listener that has been added. This hook is not called during server-side rendering because only the initial rendering is performed on the service side .

  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 operations that depend on the DOM. In most cases, however, you should avoid changing the state during this period. If you want to change the state, it is usually best to replace it with a computed attribute or watcher . The hook is not called during server-side rendering .

var test = {    //test the hook function in the test component    data () {        return {            msg: "Aha"        }    },    Template: '        <div >            <div>{{msg}}</div>            <button @click = "Changehandler" > Modify </button>        </ Div>    ',    methods:{        Changehandler () {            this.msg = this.msg + ' alex ';        }    },    BeforeUpdate () {  ///update, call this hook, apply: Get the original Dom        Console.log (document.getElementById (' app '). InnerHTML);   Get all elements    },    updated () {       ///update, call this hook, apply: Get the latest Dom        Console.log (document.getElementById (' app ') . InnerHTML);   Get all Elements    },};

When you click the button, the effect appears as follows:

  

The first is to get the update before all DOM objects under the original Div.

The second is to update all DOM objects underneath the new Div.

4, Beforedestroy and destroyed

  Beforedestroy: called before the instance is destroyed. In this step, the instance is still fully available. The hook is not called during server-side rendering .

  destroyed: Called when the Vue instance is destroyed . Once invoked, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all child instances will be destroyed. The hook is not called during server-side rendering .

var test = {    //test the hook function in the test component    data () {        return {            msg: "Aha"        }    },    Template: '        <div >            <div>{{msg}}</div>            <button @click = "Changehandler" > Modify </button>        </ Div>    ',    methods:{        Changehandler () {            this.msg = this.msg + ' alex ';        }    },    Beforedestroy () {        console.log (' Beforedestroy ');    },    destroyed () {        console.log (' destroyed ');    } ,};var App = {    data () {        return {            isshow:true        }    },    Template: '        <div>            <test v-if= "Isshow" ></Test>            <button @click = "Changehandler" > Change component's Life and death </button>        </div>    ',    methods:{        Changehandler () {            this.isshow =!this.isshow;        }    },    components:{  //Mount Test component        test    }};

The display effect is as follows:

  

When you click the button, it appears as follows:

  

The destruction and creation of components is a performance drain on the DOM in a Web page, or it is generally used with the following activation/deactivation.

5, activated and deactivated

  activated: Called when the keep-alive component is activated. The hook is not called during server-side rendering.

  deactivated: Called when the Keep-alive component is deactivated. The hook is not called during server-side rendering.

var test = {//test hook function in test component data () {return {msg: "aha Ha "}}, Template: ' <div> <div>{{msg}}</div> <button @click = "Changehandler" > Modify </button> </div> ', methods:{Changehandler () {this.msg =        This.msg + ' Alex ';    }}, activated () {Console.log (' component is activated ');    }, deactivated () {Console.log (' component deactivated ');            }};var App = {data () {return {isshow:true}}, Template: ' <div> <keep-alive> <test v-if= "Isshow" ></Test> </keep-alive> <            Button @click = "Changehandler" > Change the component's life and Death </button> </div> ', methods:{Changehandler () {        This.isshow =!this.isshow; }}, components:{//Mount Test component Test}}; 

  keep-alive The current component to produce a cache . The deactivation and activation of a component is only related to the cache and has no relation to the life cycle.

Click the button to display the following results:

  

Clicking the component again is deactivated, but the DOM does not change:

  

6, errorcaptured

Called when a bug from a descendant component is captured. This hook receives three parameters: the Error object, the component instance where the error occurred, and a string containing the source of the error. This hook can be returned false to prevent the error from continuing to propagate upward.

See also: https://cn.vuejs.org/v2/api/#选项-life cycle hooks

Three, life cycle diagram

  

The deactivation and activation of a component is only related to the cache and has no relation to the life cycle.

Life cycle Hooks

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.