本篇文章重点讲述vue组件的生命周期,主要形式是通过实例说明组件由创造到结束的过程。
vue组件周期
- beforeCreate
- created
- beforeMounte
- mounted
- beforeUpdate
- Updated
- beforeDestory
- destoryed
生命周期的主要方法就是这些(详细的讲解请参考这篇文章),我们常用的是mounted和beforeDestory这两个方法,mounted方法是指组件的初始化工作都已经完成了,运行到这个阶段,就可以获取到this中的数据和方法,并且可以对dom进行操作,我们通常是在该方法中进行ajax请求,定时器及其他的异步操作;而在beforeDestory阶段,如果有定时器,我们会在这个方法中取消定时器。
下面我们就用例子将整个流程走一遍:
<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闪现一次,点击上方按钮可停止闪烁,在控制台中会将组件从创建到销毁整个过程打印出来。
根据上面的例子,我们可以知道,在vue的生命周期中,只有与组件更新有关的方法会执行多次,创建方法,挂载方法以及卸载方法都是只会执行一次。