[Vue] Vue life cycle and its hook function

Each Vue instance must go through a series of initialization processes before being created. This process is the Vue life cycle.

vue2. Lifecycle hook functions for 0 (10)

beforeCreate:

  • After instance initialization
  • Data observer and event/watcher events have not been configured yet.

created:

  • Called after the instance has been created.
  • The instance has completed the following configuration: Data observer, operation of properties and methods, and callback of watch/event events
  • The mount phase has not yet started and the $el attribute is not currently visible.
  • In the created hook, you can operate on data. At this time, you can make an ajax request to assign the returned data to data
  • When using Vue router, you sometimes need to use < keep alive > < / keep alive > to cache the component state. At this time, the created hook will not be called repeatedly. If our sub components need to perform some operations during each loading, you can use the activated hook to trigger.

beforeMount:

  • Called before the mount starts: the relevant render function is called for the first time.

mounted:

  • el is created by the newly created VM$ el is replaced and mounted to an instance to invoke the hook.
  • If the root instance mounts an element in the document, when mounted is called, VM$ El is also in the document.
    Operate on the mounted dom in the mounted hook

beforeUpdate:

  • Called when the data is updated, which occurs before the virtual DOM is re rendered and patched. You can further change the state in this hook, which does not trigger an additional re rendering process.

updated:

  • The 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:

  • Called when the keep alive component is activated.

deactivated:

  • Called when the keep alive component is deactivated.

beforeDestroy:

  • Before the instance is destroyed, it is called. At this step, the instance is still fully available.

destroyed:

  • After the Vue instance is destroyed, it is called. After calling, everything indicated by the Vue instance will be unbound, all event listeners will be removed, and all sub instances will be destroyed.

Example display

We created a Vue root instance named app and mounted it on the dom element with page id app.

Locally register a component of child and register it in the root instance so that it can be used in the scope of the root instance.

Wrap the sub components with < keep alive > to prepare for the next test. Keep alive is a built-in component of Vue, which can keep the contained components in the state or avoid re rendering.

In vue projects, it is inevitable that there will be a list page or a search result list page. After clicking a result and returning, if the result page is not cached, it will return to the initial state when returning to the list page. However, whether the result we want is the return page or the previous search result list, we need to use vue's keep alive technology

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/Vue_js/vue.js"></script>
</head>
<body>

<div id="app">
   <p>{{ message }}</p>
   <keep-alive>
       <my-components msg="hello" v-if="show"></my-components>
   </keep-alive>
</div>

<script>
    var child = {
        template: `<div>from child: {{msg}}</div>`,
        props: ['msg'],
        data() {
            return {
                childMsg: 'child'
            }
        },
        deactivated: function () {
            console.log('component deactivated!');
            },
        activated: function () {
            console.log('component activated');
        }
    }

    var app = new Vue({
        el: '#app',
        data() {
            return {
                message: 'father',
                show: true
            }
        },
        beforeCreate: function () {
            console.group('beforeCreate Pre creation status===============>');
            var state = {
                'el': this.$el,
                'data': this.$data,
                'message': this.message
            }
            console.log(state);
        },
        created: function () {
            console.group('created Created status===============>');
            var state = {
                'el': this.$el,
                'data': this.$data,
                'message': this.message
            }
            console.log(state);
        },
        beforeMount: function () {
            console.group('beforeMount Pre mount status===============>');
            var state = {
                'el': this.$el,
                'data': this.$data,
                'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        mounted: function () {
            console.group('mounted Mount end 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 before update===============>');
            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 Update completion 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 Status before destruction===============>');
            var state = {
                'el': this.$el,
                'data': this.$data,
                'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        destroyed: function () {
            console.group('destroyed Destruction completion status===============>');
            var state = {
                'el': this.$el,
                'data': this.$data,
                'message': this.message
            }
            console.log(this.$el);
            console.log(state);
        },
        components: {
            'my-components': child,
        }
    })
</script>
</body>
</html>

create and mounted related:

  • Before created: el and data are not initialized
  • created: the initialization of data is completed, but el not
  • beforeMount: complete el and data initialization;
  • Mounted: finish mounting. (Note: the Virtual DOM (Virtual DOM) technology applied in the beforeMount stage first occupies the pit, and then renders the value when it is mounted later.)

activated and destroyed related:

We found that the activated cycle hook has been triggered because the sub component my components are wrapped in < keep alive > and triggered with the mounting of el.

Now let's disable this component for testing: since the sub component has a v-if instruction v-if = "show", we can destroy it by setting the value of show to false. Console input app show = false

Since we modified the value of data here, the beforeUpdate and updated hooks will be triggered.

We see that the deactivated hook has been triggered, indicating that it has been deactivated, which is in line with the expected results.

Destroy the Vue instance and call app$ Destroy() method can destroy it. The console test is as follows:

Destruction here does not mean "erasing", but "unbinding".

updated related:

Data changes can be monitored in beforeUpdate, but the view layer has not been re rendered, and the data of the view layer has not changed. When it is updated, the view layer is re rendered and the data is updated.

Keywords: Javascript Front-end Vue Vue.js

Added by kfir91 on Tue, 22 Feb 2022 06:58:53 +0200