[Vue] The life cycle of VM in vue and loading and destroying instances

will be created Call the beforeCreate function
Created call created function
will be mounted Call the beforeMount function
mounted (important) Call mounted function
will be updated Call the beforeUpdate function
update completed call the updated function
will be destroyed (important) Call the beforeDestory function
destroyed call the destroyed function

Commonly used lifecycle hooks:

1.mounted: send ajax requests, start timers, bind custom events, subscribe messages, etc. (initialization operations)

2.beforeDestory: clear timers, cancel custom events, unsubscribe messages, etc. (start and end work)

Regarding destroying the Vue instance:

1. No information can be seen with the help of Vue developer tools after destruction

2. Custom events will be invalid after destruction, but native DOM events are still valid

3. Generally, the data will not be manipulated beforeDestroy, because even if the data is manipulated, the update process will no longer be triggered.

Original link: https://blog.csdn.net/m0_58151273/article/details/122359649

[mounted] Mounting instance

 

<!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>demo</title>
</head>
<script type="text/javascript" src="vue.js"></script>

<body>
    <div id="box">
        <h2 :style="{opacity}">我是李逵</h2>
        <button @click="begin">开始变化效果</button>
        <button @click="stop">停止变化效果</button>
    </div>
</body>
<script type="text/javascript">
    var box = new Vue({
        el: "#box",
        data: {
            opacity:1

        },
        methods: {
            
            begin(){

                this.timer=setInterval(()=>{
                    this.opacity=this.opacity-0.01;
                    if(this.opacity<=0){
                        this.opacity=1;
                    }
                }
                ,16)
            },
            stop(){
                // 销毁掉vm(box)
                this.$destroy();
            }
        },
        // vm(box)挂载后执行
        mounted() {
                this.timer=setInterval(()=>{
                    this.opacity=this.opacity-0.01;
                    if(this.opacity<=0){
                        this.opacity=1;
                    }
                }
                ,16)
        },
        // vm(box)即将销毁时,清除掉定时器
        beforeDestory(){
            clearInterval(this.timer)
        }


    })
</script>

</html>

Guess you like

Origin blog.csdn.net/dxnn520/article/details/123226969