本篇文章重点讲述vue组件的生命周期,主要形式是经过实例说明组件由创造到结束的过程。
生命周期的主要方法就是这些(详细的讲解请参考这篇文章),咱们经常使用的是mounted和beforeDestory这两个方法,mounted方法是指组件的初始化工做都已经完成了,运行到这个阶段,就能够获取到this中的数据和方法,而且能够对dom进行操做,咱们一般是在该方法中进行ajax请求,定时器及其余的异步操做;而在beforeDestory阶段,若是有定时器,咱们会在这个方法中取消定时器。
下面咱们就用例子将整个流程走一遍:vue
<body> <div id="app"> <button @click="stop">中止闪烁</button> <p v-show="isshow">生命周期练习</p> </div> <script> new Vue({ el: '#app', data: { isshow: true, interval: null }, beforeCreate(){ //在这个阶段的特色是组件中的数据和方法获取不到 console.log('beforeCreate') console.log(this.isshow) }, created(){ console.log('created') }, beforeMount(){ console.log('beforeMount') }, mounted(){ console.log('mounted') this.interval = setInterval(()=>{ this.isshow = !this.isshow },1000) }, beforeUpdate(){ console.log('beforeUpdate') }, updated(){ console.log('updated') }, beforeDestroy(){ console.log('beforeDestroy') clearInterval(this.interval) }, destroyed(){ console.log('destroyed') }, methods: { stop(){ this.$destroy() } } }) </script> </body>
该例子想展现的效果是,文本内容每隔1s闪现一次,点击上方按钮可中止闪烁,在控制台中会将组件从建立到销毁整个过程打印出来。ajax
根据上面的例子,咱们能够知道,在vue的生命周期中,只有与组件更新有关的方法会执行屡次,建立方法,挂载方法以及卸载方法都是只会执行一次。app