(尚013)Vue的生命周期

懵懂的女人 提交于 2019-12-11 11:31:19

三个阶段:

一.初始化显示;

 

 

 

二:更新显示

 

 

 

三.死亡

 

 

 

每一个阶段都对应生命周期的回调函数(也叫勾子函数)

生命周期图示:

 

 

 

1.

 

 

 2.test013.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><!--1.vue对象生命周期    1)初始化显示        beforeCreate()        created()        beforeMount(}        mounted()    2)更新显示 this.xxx=value        beforeUpdate()        updated()    3)销毁vue实例:vm.$destory()        beforeDestory()        destory()2.常用的生命周期方法    created()/mounted():发送ajax请求,启动定时器等异步任务    beforeDestory():做收尾工作,如:清除定时器--><div id="test" >    <button @click="destroyVM">destroy vm</button>    <!--v-show显示与隐藏-->    <p v-show="isShow">赵子龙:吾乃常山赵子龙也!!!</p></div><script type="text/javascript" src="../js/vue.js"></script><script type="text/javascript">    new Vue({        el:'#test',        data:{            //每隔一秒钟这个值isShow:true改变一下            //想到技术:循环定时器            isShow:true        },        //1.初始化阶段        //测试beforeCreate()        beforeCreate(){            console.log('beforeCreate()')        },        //测试create()        created(){            console.log('created()')        },        //测试beforeMount        beforeMount(){            console.log(beforeMount())        },        //重点        mounted(){//初始化显示之后立即调用(1次)            console.log('mounted()')            //设置定时器            //需要beforeDestory()方法看得见this.intervalId            this.intervalId=setInterval(()=>{                console.log('-----------------------')                //setInterval(function(){                // this有问题,this希望是当前的vm,但是当前是window;所以要写箭头函数                //记住:一旦将一个回调函数当做参数传递,就要将回调函数写成箭头函数;                //因为箭头函数就是用来定义匿名函数的,但箭头函数的特点就是:函数内部没有自己的this,没有就用外部的this,外部的就是vm对象                this.isShow=!this.isShow            },1000)        },        //2.更新阶段        beforeUpdate(){            console.log('beforeUpdate()')        },        //测试updated()        updated(){            console.log('updated()')        },        //3.死亡阶段        //生命周期回调函数    //重点        beforeDestroy(){ //死亡之前调用(1次)            //清除定时器            clearInterval(this.intervalId)        },        destroyed(){            console.log('destroyed()')        },    methods:{        destroyVM(){            //干掉vm            //观察控制台console发现定时器还在运行,出现了内存泄漏            //需要清除定时周期            this.$destroy()        }    }    })</script></body></html>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!