vue基础part9

vue声明周期

对vue生命周期简单了解
初始化阶段

​ beforeCreate

​ Created

​ beforeMount

​ mounted

数据更新阶段

​ beforeUpdate

​ updated

销毁

​ beforeDestroy

​ destroyed

代码说明:

页面显示按钮控制销毁vue实例 p标签定时(1s)显示在页面上,销毁实例后,不再执行定时任务。按下按钮的那一瞬间,页面如果显示p标签内容,则后续一直显示,如果那一瞬间是消失的,则会一直不显示(display :none)

 	<div id="model">
        <button @click="destroyVm"> destroy vm</button>
        <p v-show="isShow">尚硅谷it教育</p>
    </div>

定时器任务会返回它的定时器id 通过this可以提升变量的作用域,让它能在beforeDestroy方法中能访问到,直接销毁实例并不会停止定时器,我们仍需要在销毁之前去把清楚定时器

new Vue({
            el:'#model',
            data:{
                isShow:true
            },
            beforeCreate(){
                console.log('beforeCreate')
            },
            Created(){
                console.log('Created')
            },
            beforeMount(){
                console.log('beforeMount')
            },
            mounted(){
                this.instervalId= setInterval(()=>{
                    console.log('----------------')
                    this.isShow = !this.isShow
                },1000)
            },
            beforeUpdate(){
                console.log('beforeUpdate')
            },
            updated(){
                console.log('updated')
            },
            beforeDestroy(){
                clearInterval(this.instervalId)
                console.log('beforeDestroy')
            },
            destroyed(){
                console.log('destroyed')
            },
            methods:{
                destroyVm(){
                    this.$destroy()
                }
            }
        })

页面控制台打印结果:

原文地址:https://www.cnblogs.com/wuloucha/p/13460898.html