Detailed vue life cycle: from entry to the master

Vue life cycle

In the process of learning vue, vue life cycle can be described as the most important part will learn.
Vue each instance when it is created to go through a series of initialization process, for example, need to set the monitor data, compiled templates, examples will be mounted to the DOM and DOM updates when the data changes. But also run some function called the life cycle of the hook in the process, which gives the user the opportunity to add your own code at different stages. The picture below presumably everyone is familiar

Lifecycle icon :

Here Insert Picture Description
Explain : First, create an vueinstance, a first initialization operation, the initialization is only initialize its own life cycle events and , after initialization is complete, start the second initialization, this time will be data, computed, methodsand so the observation data ( data observer), the properties and methods of operation, event/watchevent callback to initialize the injection , after completion, will check whether el option is specified, if specified, or designated useless but called vm.$mout("el")upon to continue to see if the specified templatetemplate, specify if useless , put outside HTMLas a templatecompiler, if specified, will be templaterendered to the renderfunction (of course, we can not use template, direct use renderfunction to create a template), then create vm.$el, replace el, this time it has been mounted finished, if the data change, the virtual DOMre-render and apply the update, when you call the method of destruction is unbound, the destruction of sub-assemblies and event listeners.

Lifecycle hook

All life cycle hook automatically bind thiscontext to an instance, so you can access the data on the properties and methods of operation, therefore, do not hook function definitions when using the arrow function, arrow useless function this, may be errorUncaught TypeError: Cannot read property of undefined
Here Insert Picture Description

I turn introduces eight lifecycle hook down here!

  • beforeCreate

    After instance initialization, data observation ( data observer) and event/watchis invoked before the event configuration.

<div id="app">
   {{ name }}
</div>
const vm = new Vue({
    el:"#app",
    data:{
        name:"monk"
    },
    beforeCreate(){
        console.log(this.name);
        console.log(this.handleFunction)
        console.log("--beforeCreate--")
    },
    methods: {
        handleFunction(){
            console.log("我是一个方法!");
        }
    },
    watch: {
        name:{
            handler(){
                console.log("我已经开始监听侦听name属性啦");
            },
            immediate:true
        }
    },
})

Print order : After initialization example, the observation data (data observer) and event / watch event is invoked before configuration.

undefined
undefined
--beforeCreate--
我已经开始监听侦听name属性啦
  • created

    Called immediately after an instance is created. In this step, the following configuration examples have been completed: the observed data (data observer), the operational properties, and methods, event / watch event callbacks.

    If the method is to call methods in the first time, or the data in the operation data, this may be operated hooks . Note that, when you do this hook, mount the stage has not yet begun, $ el property is not currently visible. In this case, the data request, the request is assigned to the data value back to the data.

<div id="app">
  {{ name }}
</div>
const vm = new Vue({
    el:"#app",
    data:{
        name:"monk"
    },
    created(){
        console.log(this.name);
        console.log(this.handleFunction)
        console.log(this.$el);
        console.log('----------created-------');
    },
    methods: {
        handleFunction(){
            console.log("我是一个方法!");
        }
    },
    watch: {
        name:{
            handler(){
                console.log("我已经开始监听侦听name属性啦");
            },
            immediate:true
        }
    },
})

Print order : now complete the following configuration: the observed data (data observer), the operational properties, and methods, watch / event event callbacks.

我已经开始监听侦听name属性啦
monk
ƒ handleFunction(){console.log("我是一个方法!");}
undefined
----------created-------
  • beforeMount

    It is called before beginning to mount, when the template has been compiled, but did not replace the generated template elcorresponding elements. In the hook function, you can get into the template of the most original state. At this point, you can get vm. $ El, just as the old template

const vm = new Vue({
  el: '#app',
  beforeMount () {
    console.log(this.$el);
  }
})

Print result : You can get the vm $ el, just as the old template.

<div id="app">{{ name }}</div>
  • mounted

    elIt was newly created vm.$elto replace, and mount the hook to call up after instance. In the hook function in vm.$elthe new template. After executing the hook function, representing the instance has been completely created. If you want the first time, the operation on the page dom node, can operate this function hook

const vm = new Vue({
  el: '#app',
  mounted () {
    console.log(this.$el);
  }
})

Print result : At this point of the template is already a new template

<div id="app">monk</div>
  • beforeUpdate

    Called when the data update occurs before the virtual DOM patch. At this point the data has been updated, but has not yet updated DOM

<div id="app">
  {{ name }}
</div>
const vm = new Vue({
    el:"#app",
    data:{
        name:"monk"
    },
    beforeUpdate(){
        console.log(this.name);
        console.log(this.$el);
    }
})
vm.name = "young monk"

Print result : At this point the data has been updated dom and virtual, but real Dom has not been updated

young monk
<div id="app">young monk</div>
  • updated

    After re-rendered data change caused the DOM, it will execute the hook function. At this time, data synchronization and dom. By way of example do not need to feel, Hey hey

  • beforeDestroy

    Called before destroy instance. In this step, the instance is still fully available. Can the hook function, clear the timer.

<div id="app">
  {{ name }}
</div>
const vm = new Vue({
    el:"#app",
    data:{
        name:"monk",
        timer:null
    },
    created(){
        this.timer = setInterval(()=>{
            console.log("定时器执行!!!")
        },1000)
    },
    beforeDestroy() {
        clearInterval(this.timer)  
    }
})

Print the results : After creating an instance of the timer will always execute the contents, until the implementation of the destruction function vm.$destroy(), eliminating the timer ends the execution

  • destroyed

    Vue instance calls after the destruction. After the call, everything will de-binding indication Vue instance, all event listeners will be removed.

Published 34 original articles · won praise 150 · views 20000 +

Guess you like

Origin blog.csdn.net/Newbie___/article/details/105347733