Detailed explanation of Vue life cycle

Posted by praxiz on Fri, 11 Feb 2022 15:56:44 +0100

Mount (initialize related properties)

1. beforeCreate

Triggered when the instance of new Vue has not been created and the specific configuration of Vue instance has not been carried out according to the configuration object

At this time, the option object of the component has not been created, and el and data have not been initialized, so there is no way to access the methods, data, computed and other methods and data.

2. created

Triggered when the Vue instance is created. It is called immediately after the instance is created

The instance has completed the following configuration:

Operation of data observer, properties and methods, and callback of watch/event events.

At this time, the mount phase has not yet started, so the attribute of $el is invisible. Therefore, at this time, we can call the method method method to change the value in data and obtain the calculated attribute in calculated.

3. beforeMount

Triggered when the instance is mounted. When the instance and app are mounted, they are called before mounting, and the relevant render function is called for the first time (virtual DOM)

The instance has completed the following configuration

Compile the template, generate html from the data and template in data, and complete the initialization of el and data,

But it is not mounted on the page at this time.

4. mounted

Triggered when the container is initialized and the container template is ready. Mount the page and render the html into the page. At this time, you can perform some request operations. This event will be executed only once.

Update (change operation of element or component)

1. beforeUpdate

Triggered before updating the data in data. We can verify whether the latest data updated by users is correct in the beforeUpdate life cycle

2. updated

Execute when the data is updated

The virtual DOM is re rendered and patched due to data changes, after which the hook will be called

When this hook is called, the component DOM has been updated, so you can now perform DOM dependent operations. However, in most cases, you should avoid changing state during this period. If you want to change the state accordingly, it is usually best to use the calculated attribute or watcher instead.

Destroy (destroy related attributes)

1.beforeDestroy

Triggered before destroying Vue instances

At this time, we can release and empty the data saved by variables. At this step, the instance is still fully available

Generally, some reset operations are performed in this step, such as clearing the timer in the component and listening dom events.

2.destroyed

After destroying the Vue instance, it triggers and calls after the instance is destroyed.

After calling, all event listeners will be removed and all sub instances will be destroyed. The hook will not be called during server-side rendering

Example:

<!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>Document</title>
</head>
<body>
    <div id="app">
        <aaa></aaa>
    </div>

    
    <template id="aaa">
        <div>
            <p class="myp">A assembly</p>
            <button @click="destroy">destroy</button>
            <input type="text" v-model="msg">
            <p>msg:{{msg}}</p>
        </div>
    </template>



</body>
<script src="./vue.js"></script>

<script>
    //Life cycle: initialization phase, running phase, destruction phase
    Vue.component("aaa",{
        template:"#aaa",
        data:function(){
            return {msg:'hello'}
        },
        timer:null,
        methods:{
            destroy:function(){
                this.$destroy()//
            }
        },
        beforeCreate:function(){
            console.log('beforeCreate:just new Vue()Later, at this time, the data has not been mounted, but an empty shell')           
            console.log(this.msg)//undefined
            console.log(document.getElementsByClassName("myp")[0])//undefined
        },
        created:function(){
            console.log('created:At this time, the data can be used or changed,Changing data here will not trigger updated function')
            this.msg+='!!!'
            console.log('Here, you can count down the second chance to change the data before rendering without triggering other hook functions. Generally, you can obtain the initial data here')
            console.log('Next, start to find the template corresponding to the instance or component, and compile the template into virtual dom Put into render Prepare rendering in function')
        },
        beforeMount:function(){
            console.log('beforeMount: fictitious dom It has been created and will be rendered soon,Data can also be changed here without triggering updated')
            this.msg+='@@@@'
            console.log('Here, you can change the data for the last time before rendering without triggering other hook functions. Generally, you can obtain the initial data here')
            console.log(document.getElementsByClassName("myp")[0])//undefined
            console.log('Let's start render´╝îRender reality dom')
        },
        // render:function(createElement){
        //     console.log('render')
        //     return createElement('div','hahaha')
        // },
        mounted:function(){ 
            console.log('mounted: At this point, the component has appeared in the page, data and reality dom It's all taken care of,The events have been mounted')
            console.log(document.getElementsByClassName("myp")[0])
            console.log('You can operate it here dom Wait for things...')

        //    this.$options.timer = setInterval(function () {
        //        console.log('setInterval')
        //         this.msg+='!'  
        //    }.bind(this),500)
        },
        beforeUpdate:function(){
        	//The data cannot be changed here, otherwise it will fall into an endless loop
            console.log('beforeUpdate:Triggered before re rendering')
            console.log('then vue Virtual dom The mechanism will rebuild the virtual machine dom With the last virtual dom Tree utilization diff The algorithm is compared and re rendered')         
        },
        updated:function(){
        	//The data cannot be changed here, otherwise it will fall into an endless loop
            console.log('updated:The data has been changed, dom Also re render complete')
        },
        beforeDestroy:function(){
            console.log('beforeDestory:Execute before destruction( $destroy Method is executed when it is called),Usually deal with the aftermath here:Clear timers, clear non instruction bound events, and so on...')
            // clearInterval(this.$options.timer)
        },
        destroyed:function(){
            console.log('destroyed:Data binding and listening of components...It's all gone,Only left dom Empty shell, you can also deal with the aftermath here')
        }
    })


    
    new Vue({
    }).$mount('#app')


</script>
</html>