一、生命周期分析
- 初始化显示
- beforeCreate()
- created()
- beforeMount()
- mounted()
- 更新状态: this.xxx = value
- beforeUpdate()
- updated()
- 销毁 vue 实例: vm.$destory()
- beforeDestory()
- destoryed()
二、常用的生命周期方法
- created()/mounted(): 发送 ajax 请求, 启动定时器等异步任务
- beforeDestory(): 做收尾工作, 如: 清除定时器
代码:
<div>
<button @click="destoryVue">destory vue</button>
<p v-show="isShowing">{{msg}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
var vue = new Vue({
el: 'div',
data: {
msg: '你在忙什么呢',
isShowing: true,
persons: []
},
beforeCreate () {
console.log('beforeCreate() msg=' + this.msg)
},
created () {
console.log('created() msg='+this.msg)
this.intervalId = setInterval(() => {
console.log('-----')
this.isShowing = !this.isShowing
}, 1000)
},
beforeMount () {
console.log('beforeMount() msg='+this.msg)
},
mounted () {
console.log('mounted() msg='+this.msg)
},
beforeUpdate() {
console.log('beforeUpdate isShowing='+this.isShowing)
},
updated () {
console.log('updated isShowing='+this.isShowing)
},
beforeDestroy () {
console.log('beforeDestroy() msg='+this.msg)
clearInterval(this.intervalId)
},
destroyed () {
console.log('destroyed() msg='+this.msg)
},
methods: {
destoryVue () {
vue.$destroy()
}
}
})
</script>