Teaching girlfriend to learn [vue life cycle hook function]

Written in front : I am "Sailing to the Sea", this nickname comes from my name and the name of my girlfriend. I love technology, open source, and programming. 技术是开源的、知识是共享的.

This blog is a little summary and record of your learning. If you are interested in Java and algorithms , you can follow my development and we will study together.

用知识改变命运,让我们的家人过上更好的生活.

Insert picture description here

1. The life cycle of vue

Just as humans have life cycles, a program itself and every instance and component in a program have a life cycle.

A person's life cycle begins at birth and ends at death. In the decades from birth to death, many major events will occur. These events will affect some people or the entire world.

对于一个程序或Vue.js中的一个实例来说,其生命周期开始于创建,当新建一个实例的时候,生命周期就开始了;而当销毁一个实例之后,生命周期就结束了。

Each Vue instance undergoes a series of initialization processes when it is created-for example, you need to set up data monitoring, compile templates, mount the instance to the DOM, and update the DOM when the data changes. At the same time, some functions called lifecycle hooks will be run in this process, which gives users the opportunity to add their own code at different stages.

Second, the hook function

Vue instance from the creation to the process of destruction, these processes will be accompanied by the self-call of some functions. Call these functions 钩子函数.

Why is it called a hook? The reason is that you need to respond to a preset code after an instance event occurs, that is, a hook hooks the state or event of an instance.

Insert picture description here

1. The life cycle of the creation phase

beforeCreate

After the instance is initialized, the data observer and event / watcher events are called before configuration. 此时的 data 和 methods 中的 数据都还没有没初始化.

created

Called immediately after the instance is created. In this step, the instance has completed the following configuration: data observer (data observer), attribute and method operations, watch / event event callback. That is 此时 data 和 methods已经可以初始化完成了. However, the mount phase has not yet begun, and the $ el attribute is not currently available. The page has not been rendered.

note:

If you want to call a method in methods, or manipulate data in data, you can only operate in created at the earliest.

beforeMount

Called before the mount begins. At this time 页面上还看不到真实的数据, because the template is compiled in memory, but the template has not been rendered to the page.

note:

When beforeMount is executed, the elements on the page have not been actually replaced, and some template strings written before are displayed.

mounted

Called after the instance is mounted, at this time el is replaced by the newly created vm. $ El. This time 据已经真实渲染到页面上了.

mounted is the last life cycle function during instance creation. When mounted is executed, it means that the instance has been completely created.

note:

mounted does not guarantee that all subcomponents will be mounted together. If you want to wait until the entire view is rendered, you can use vm. $ NextTick inside mounted:

mounted: function () {
  this.$nextTick(function () {
    // Code that will run only after the
    // entire view has been rendered
  })
}

2. Life cycle of the operation phase

beforeUpdate

Called when data is updated, before the patching of the virtual DOM. At this time 页面上数据还是旧的,但是 data 数据是最新的, the page has not been synchronized with the latest data.

This is suitable for accessing the existing DOM before updating, such as manually removing the added event listener.

updated

The virtual DOM is re-rendered and patched due to data changes, after which the hook is called. At this time 页面上数据已经替换成最新的.

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

3. Life cycle of the destruction phase

beforeDestroy

Called before the instance is destroyed. At this step, the instance is still fully available.

destroyed

Called after the instance is destroyed. After the hook is called, all instructions corresponding to the Vue instance are unbound, all event listeners are removed, and all child instances are also destroyed.

Three, code examples

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

<head>
    <meta charset="UTF-8">
    <title>生命周期钩子函数</title>
    <script type="text/javascript" src="js/vue.js"></script>
    <style>
        .btn-update {
            text-align: center;
            color:white;
            background-color: green;
            font-size: 15px;
            margin-top: 10px;
        }
        .btn-destroy {
            text-align: center;
            color: white;
            background-color: red;
            font-size: 15px
        }
        .btn-wrap {
            margin: 10px auto;
            width: 32%;
        }
        .str {
            background-color: skyblue;
            color: white;
            font-size: 30px;
            width: 18%;
            
        }
    </style> 
</head>

<body>
    <div id="app">
        <div class='str'>{{msg}}</div>
        <button class='btn-update' @click='update'>更新</button>
        <button class='btn-destroy' @click='destroy'>销毁</button>
    </div>
    <script type="text/javascript">
        
        var vm = new Vue({
            el: '#app',
            data: {
                msg: '我是扬帆向海'
            },
            methods: {
                update: function () {
                    this.msg = '我被改变了~~~';
                },
                destroy: function () {
                    this.$destroy();
                }
            },
            beforeCreate: function () {
                console.log('beforeCreate---创建前状态');
            },
            created: function () {
                console.log('created---创建完毕状态');
            },
            beforeMount: function () {
                console.log('beforeMount---挂载前状态');
            },
            mounted: function () {
                console.log('mounted---挂载结束状态');
            },
            beforeUpdate: function () {
                console.log('beforeUpdate---数据更新之前状态');
            },
            updated: function () {
                console.log('updated---数据更新完成状态');
            },
            beforeDestroy: function () {
                console.log('beforeDestroy---实例销毁之前状态');
            },
            destroyed: function () {
                console.log('destroyed---实例销毁完成状态');
            }
        });
    </script>
</body>

</html>

During the page loading process, four hook functions in the creation phase are executed in sequence:

Insert picture description here

The first page load will trigger the beforeCreate, created, beforeMount, mounted hook functions. DOM rendering is already done in mounted.

Effect diagram of the life cycle hook function loading process

Insert picture description here


Due to the limited level, this blog will inevitably have deficiencies, I urge you guys to let me know!

101 original articles published · 5103 likes · 1.23 million views

Guess you like

Origin blog.csdn.net/weixin_43570367/article/details/105565891