Summary of Vue knowledge points (18)-life cycle (super detailed)

Codewords are not easy, and helpful students hope to pay attention to my WeChat official account: Code Program Life, thanks!

The theme of this issue is the life cycle of Vue .
Let me talk about what life cycle is .
This is what Baidu Encyclopedia says:

Life cycle refers to the birth, aging, sickness and death of an object.

Each of us will go through the process of birth, old age, sickness and death. This is a fact that no one can get rid of.
The same is true for programs. A page and a component will also have a process of birth , change, and destruction . This is their life cycle. The procedure originally follows the objective facts and laws in human life.

Let's take a look at the life cycle in Vue.
This is the diagram of the official document:
Insert picture description here
This diagram may seem a little difficult because it is in pure English , and some of the concepts are difficult to understand. It will carry out the development process of the entire Vue project , so if you have a poor foundation , it is not necessary Get it now.

The official document also says this:

You don't need to understand everything right away, but as you continue to learn and use, its reference value will become higher and higher.

Not all of the life cycle hook functions need to be used proficiently, because some hook functions are not used most of the time. We only need to understand briefly, but there are also some frequently used ones that we need to master.

Let's talk about it in turn from top to bottom according to the illustrated process:

beforeCreate

This stage is after the instance is initialized and before the component is created. At this time, the data observation and event mechanism are not formed, and the DOM node cannot be obtained.

This is the stage before creation , and it is not very practical at this stage, because many event mechanisms and data observations are not formed at this stage , and DOM cannot be obtained , so we only need to understand it briefly.

created

It is called immediately after the instance is created. In this step, the instance has completed the following configurations: data observer, calculation of properties and methods, and watch/event event callbacks. However, the mount phase has not yet started, and $el property is not yet available.

This is the stage after creation . At this stage, the Vue instance has been created, but the DOM element is still not available .
This hook function is used very, very much , you can request the back-end interface in this function , or receive the value of component communication . It is a very, very important stage, many things can be done, and most dynamic projects are frequently used.

beforeMount

Called before the start of the mount: the related render function is called for the first time. This hook is not called during server-side rendering.

This is the stage before mounting . At this stage, although we still can't get the specific DOM element, the root node of vue mounting has been created . The following Vue operations on the DOM will continue around this root element. The beforeMount stage is transitional. Generally, a project can only be used once or twice.

mounted

Called after the instance is mounted, at this time el is replaced by the newly created vm.$el. If the root instance is mounted on an element in a document, vm.$el is also in the document when mounted is called.
Note that mounted does not guarantee that all subcomponents are also 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
  })
}

This is the post-mounting stage. Mounted is also a function that we usually use a lot . Generally, our asynchronous requests are written here. At this stage, both the data and the DOM have been rendered.

beforeUpdate

Called when the data is updated, before the virtual DOM is patched. This is suitable for accessing the existing DOM before the update, such as manually removing the added event listener.
This hook is not called during server-side rendering, because only the first rendering will be performed on the server-side.

This is the stage before the update . At this stage, vue follows the principle of data-driven DOM . Although the beforeUpdate function does not update the data immediately after the data is updated, the data in the DOM will change. This is the function of Vue two-way data binding .

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 operations that depend on the DOM. However, in most cases, you should avoid changing the status during this period. If you want to change the state accordingly, it is usually best to use calculated attributes or watchers instead.
Note that updated does not guarantee that all child components will be redrawn together. If you want to wait until the entire view is redrawn, you can use
vm.$nextTick in updated :

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

This hook is not called during server-side rendering.

This is the post-update stage, in which the DOM will be synchronized with the changed content .

beforeDestroy

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

This hook is not called during server-side rendering.

This is the stage before destruction. In the previous stage, Vue has successfully driven DOM updates through data . When we no longer need Vue to manipulate the DOM, we need to destroy Vue, that is, to clear the association between the vue instance and the DOM, and call the destroy method to destroy The current component. Before destruction, the beforeDestroy hook function will be triggered.

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 sub-instances are also destroyed.

This hook is not called during server-side rendering.

This is the post-destruction stage. After destruction, the destroyed hook function will be triggered to perform some operations.

The idea of ​​vue's life cycle runs through the development of components. By familiarizing its life cycle with different hook functions, we can accurately control the data flow and its impact on the DOM; the idea of ​​vue life cycle is a vivid embodiment of Vnode and MVVM And inheritance.

Above we briefly described the eight major stages of the Vue life cycle , which are before creation, after creation, before mounting, after mounting, before updating, after updating, before destroying, and after destroying . This is not the entire life cycle, and there are some that are not very useful, so there is no detailed explanation. Students in need can consult the official documents.
Insert picture description here

Let's use the code to actually show the various stages of the life cycle.

<style>
    .active {
    
    
        color:#f00
    }
</style>
  <div id="app">
        <App></App>
    </div>
<script>
    Vue.component('Test',{
    
    
        data () {
    
    
            return {
    
    
                msg:'Hello',
                isRed:false
            }
        },
        methods: {
    
    
            handleClick(){
    
    
                this.msg = 'msg被改变了';
                this.isRed = !this.isRed;
            }
        },
        template:`
            <div>
                <button @click='handleClick'>改变</button>
                <h3 :class='{active:isRed}'>{
     
     {msg}}</h3>
            </div>
        `,
        beforeCreate () {
    
    
            console.log("组件创建之前",this.$data);
        },
        created () {
    
    
            // 非常重要的事情,可以在此时发送ajax请求后端的数据
            console.log("组件创建完成",this.$data);
        },
        beforeMount () {
    
    
            // 即将挂载Dom
            console.log("Dom挂载之前",document.getElementById('app'));
        },
        mounted () {
    
    
            // Dom挂载完成,
            // 也可以发送ajax
            console.log("Dom挂载完成",document.getElementById('app'));
        },
        beforeUpdate () {
    
    
            // 可以获取数据更新之前的Dom
            console.log('数据更新之前的Dom',document.getElementById('app').innerHTML);
        },
        updated () {
    
    
            // 可以获取数据更新之后的Dom
            console.log('数据更新之后的Dom',document.getElementById('app').innerHTML);
        },
        beforeDestroy () {
    
    
            console.log('销毁之前',);
        },
        destroyed () {
    
    
            console.log('销毁完成');
        }

    })

    const App = {
    
    
        data () {
    
    
            return {
    
    
                isShow:true
            }
        },
        methods: {
    
    
            click(){
    
    
                this.isShow = !this.isShow;
            }
        },
        components: {
    
    
            
        },
        template:`
            <div>
                 <Test v-if='isShow'></Test>
                <button @click='click'>销毁</button>
            </div>
        `,
    }
    new Vue({
    
    
        el:'#app',
        data:{
    
    

        },
        components:{
    
    
            App
        }
    });
</script>

We simply wrote a global component Test and a local component App . In addition to the regular output statements , we also wrote two buttons , one for change and one for destruction . Mainly to better look at the update phase and the destruction phase in the life cycle .

This is the page content after page initialization .
Insert picture description here

This is the page content after clicking the change button .
Insert picture description here
This is the page content after clicking the destroy button .
Insert picture description here

After each stage is demonstrated through the code, it is quite clear.

When we write the project, we must always keep in mind that there are also life cycle hook functions available. In fact, the meaning of life cycle functions is to facilitate the operation of developers. At each stage, many operations we want to complete can be performed.

This issue has more content , because the knowledge point of life cycle is very, very important . Whether it is an interview or actual business development , it is very useful , and it is also difficult. If you are just starting to learn, Follow the official Vue prompt: you don't need to figure out everything right away, but as you continue to learn and use, its reference value will become higher and higher.


There is a WeChat mini program course design, complete design needs, contact personal QQ: 505417246

Pay attention to the following WeChat public account, you can receive WeChat applet, Vue, TypeScript, front-end, uni-app, full stack, Nodejs, Python and other practical learning materials. The
latest and most complete front-end knowledge summary and project source code will be released to the WeChat public as soon as possible No., please pay attention, thank you!

Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46171043/article/details/112432109