Start with a flow chart of the vUE website to introduce the life cycle



It must be pretty official, but it’s hard to understand the vue lifecycle hook functions from a single diagram. But don’t worry, this article uses a simple and direct example to understand this diagram.


Take 10 minutes to read on, and trust me you will learn something. 😁 😁)

There are 10 lifecycle hooks for Vue2.0:

  • BeforeCreate: Called after the instance is initialized and before the Event/Watcher event is configured.
  • Created: called after an 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.
  • BeforeMount: Called before the mount begins the associated render function is called for the first time.
  • mounted: el Specifies the newly created VM.El is also in the document.
  • BeforeUpdate: Called when data is updated and occurs before the virtual DOM is re-rendered and patched. You can further change the state in this hook without triggering additional rerendering.
  • 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.
  • Activated: activated when the keep-alive component is activated.
  • Deactivated: Activated when the keep-alive component is disabled.
  • BeforeDestroy: Called before instance destruction. At this step, the instance is still fully available.
  • Destroyed: 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.

Come on code! The code can run directly.

<! DOCTYPE html> <html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Vue-LifeClyle</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>

<body>
    <div id="app" class="jing">
        <p>{{message}}</p>
        <keep-alive>
            <jh-component msg="June 9, 2017" v-if="show"></jh-component>
        </keep-alive>
    </div>
</body>
<script>
    var haohao = {
        template: '<div>from haohao: {{msg}}</div>',
        props: ['msg'],
        deactivated: function() {
            console.log('component deactivated! ');
        },
        activated: function() {
            console.log('component activated'); }}; var app = new Vue({ el:'#app',
        data: function() {
            return {
                message: 'jingjing',
                show: true// Control whether child components display}; }, beforeCreate:function() {
            console.group('beforeCreate the state before Vue instance creation ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(state);
        },
        created: function() {
            console.group('Created Vue instance status after creation ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(state);
        },
        beforeMount: function() {
            console.group('beforeMount State before mounting ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        mounted: function() {
            console.group('Mounted status ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        beforeUpdate: function() {
            console.group('beforeUpdate status beforeUpdate ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
            console.log('beforeUpdate = ' + document.getElementsByTagName('p')[0].innerHTML);
        },
        updated: function() {
            console.group('Updated completed status ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
            console.log('Updated = ' + document.getElementsByTagName('p')[0].innerHTML);
        },
        beforeDestroy: function() {
            console.group('beforeDestroy Pre-destruction state ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        destroyed: function() {
            console.group('Destroyed completion state ————————————————————');
            var state = {
                'el': this.$el.'data': this.$data.'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        components: {
            'jh-component': haohao
        }
    });
</script>

<style>
    .jing {
        font-size: 50px;
        font-weight: bolder;
    }
</style>

</html>
Copy the code

The code structure is not hard to understand

Create a Vue root instance of app and mount it on the Dom element of the page id app. A component named Haohao is then locally registered and registered in the root instance to be used in the scope of the root instance. Wrap the child component with

in preparation for the next test.

About < keep alive – > questions give you too much here, you can refer to the following two articles 1, 2, www.jianshu.com/p/4b55d312d zhuanlan.zhihu.com/p/96740001…

OK, at this point we can open developer tools in Chrome and start testing!


1, beforeCreate and created

  • beforeCreateExecution time:dataandelAre not initialized, and the value isundefined
  • createdExecution time:VueInstance observed data objectdataAlready configured and availableapp.messageValue, butVueThe root used by the instanceDOMThe elementelIt’s not initialized yet

2. BeforeMount and Mounted, and activated and deactivated

  • BeforeMount: data and EL are initialized, but {{message}} shows that el is not rendering data. This is where the Virtual DOM is applied, and the pits are captured first. The value will be rendered later when mounted

  • Mounted: The EL has been rendered and mounted to the instance

  • We see component Activated printed on the console, indicating that the child JH-Component is wrapped with

    and triggered when el is mounted.

  • Show = false on the console. Let’s see what happens.

  • How’d it go? Did you find anything? 😉 😉 😉
  • Because we changed it heredataValue, so it will triggerbeforeUpdateandupdatedThe hook function, regardless of the two functions, we see that the Deactivated hook is activated<keep-alive>It has been discontinued.

    At the same time, our child components will disappear.


BeforeUpdate and updated

  • Let’s continue typing on the consoleapp.message = 'haohao'
  • We found thatbeforeUpdateandupdatedFires,elThe data has been rendered, but according to the console printed informationbeforeUpdate = jingjingwhileupdated = haohaoKnow, only whenupdatedThe hook is called when the componentdomBefore it gets updated.


BeforeDestroy and destroyed

  • Enter on the consoleapp.$destroy()It can bevueInstance destruction, but we find pre – and post-destruction instancesdomThe structure has not changed at all, but the change has already happened elsewhere.
  • The author checked the official documentation description: After the instance was destroyed,VueEverything indicated by the instance is unbound, all event listeners are removed, and all subinstances are destroyed.

  • Let’s do the last step to confirm that.
  • Now enter on the consoleapp.message = 'jingjing'The findings are as follows:

  • We changeddataIn themessageProperty, but the DOM has no response. instructionsVueEverything indicated by the instance has been unbound. Finally 😄😄😄

Write in the last


The author is only a big white front (● – ●) this article is the first article, if there is a mistake in the text, please forgive me, point out the error is better, let the new man more than a learning opportunity. 😊 😊

This article is very superficial, but if you need to learn more about it, check out OBKoro’s article on Vue’s hook functions [routing navigators, keep-alive, lifecycle hooks].

I hope you can move your hands and click “like” before you go, your support is the biggest encouragement to me!!


Reference documentation

  • Cn.vuejs.org/v2/api/# options -…