Vue实例生命周期

1,初始化显示:

①  beforeCreate()

② created()

③ beforeMount()

④ mounted()

2,更新状态:this.xxx = value

① beforeUpdate()

② updated()

3,销毁 Vue 实例:vm.$destory()

① beforeDestory()

② destoryed()

4,常用的生命周期方法

1)created() / mounted(),发送 ajax 请求,启动定时器等异步任务

2)beforeDestory():收尾工作,如 清除定时器等。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
        <button @click="destoryVue">destory vue实例</button>
        <p v-show="isShow">{{msg}}</p>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var vm=new Vue({
            el:'#app',
            data:{
                msg:"Hello,World.",
                isShow:true
            },
            beforeCreate(){
                console.log("beforeCreate,msg:",this.msg)
            },
            created(){
                console.log("Created,msg:", this.msg);
                this.intervalId=setInterval(()=>{
                    console.log("*********");
                    this.isShow=!this.isShow;
                },1000)
            },
            updated(){
                console.log("updated,msg:", this.msg);
            },
            beforeDestroy(){
                console.log('beforeDestroy,msg:',this.msg)
                clearInterval(this.intervalId);
            },
            destroyed(){
                  console.log('destroyed,msg:', this.msg)
            },
            methods:{
                destoryVue(){
                    vm.$destroy();
                }
            }
        })
    </script>
</body>
</html>

 打印结果:

 

posted @ 2021-02-01 23:43  shanlu  阅读(68)  评论(0编辑  收藏  举报