Vue的生命周期:
生命周期有三个大的阶段,即:
- 初始化显示
- 更新显示
- 死亡
这三个阶段在上图做了划分,每一个阶段都会对应一些生命周期的回调函数(也叫 勾子)如下:
大家也可以结合上图看
首先要创建Vue实例,有了Vue之后
- 初始化阶段 (只执行一次)
- beforeCreate()
- created()
- beforeMount()
- mounted()
- 更新状态: this.xxx = value (会执行n次)
- beforeUpdate()
- updated()
- 销毁 vue 实例: vm.$destory() (执行一次)
- beforeDestory()
- destoryed()
常用的生命周期方法
- created()/mounted(): 发送 ajax 请求, 启动定时器等异步任务
- beforeDestory(): 做收尾工作, 如: 清除定时器
测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Vue的生命周期</title>
<style>
</style>
</head>
<body>
<div id="test">
<button @click="destroyVM()">destory vue</button>
<p v-show="isShow">2020年要到了!!!</p> <!--显示标签-->
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript ">
new Vue({
el:'#test',
data:{
isShow:true,
},
//1.初始化阶段
beforeCreate (){
console.log('beforeCreate()')
},
created () {
console.log('created()')
},
beforeMount (){
console.log('beforeMount ()')
},
mounted(){//初始化显示之后立即调用
this.intervalID = setInterval( () => { //this指代VM实例,只要是回调函数就写箭头函数,因为箭头函数没有自己的this,因此只能用外部的
console.log("---------")
this.isShow= !this.isShow
},1000)
},
//2.更新阶段
beforeUpdate (){
console.log('beforeUpdate()')
},
updated () {
console.log(' updated()')
},
//死亡阶段
beforeDestroy(){
//清除定时器
clearInterval(this.intervalID)
},
destroyed () {
console.log(' destroyed()')
},
methods:{
destroyVM(){
//干掉VM
this.$destroy()//这样会造成内存泄露,定时器还在不停执行
}
}
})
</script>
</body>
</html>