生命周期函数:
是Vue在关键时刻帮我们调用的一些特殊名称的函数;生命周期函数的名称不可修改,但函数的具体内容是程序员根据需要编写的;
生命周期函数中的this指向的就是vue的实例vm 或 组件实例对象;
生命周期函数一共有8个,分为三个阶段:
挂载期:(4个) beforeCreate,created,beforeMount,mounted;
更新期:(2个) beforeUpdate,updated;
销毁期:(2个) beforeDestroy,destroyed;
beforeCreate:在数据监控和数据代理之前,此时无法通过vm访问到data中的数据和methods中的方法;
created:已经完成数据监控和数据代理,可以使用data中的数据和methods中的方法;
beforeMount:Vue已经解析模板生成虚拟DOM,但还没有转为真实DOM,此时页面呈现的是未经过Vue编译的DOM结构,对所有DOM的操作都不会奏效;
mounted: 虚拟DOM已经转为真实DOM插入页面,所有对DOM的操作都有效;
beforeUpdate: 当data发生改变时调用,此时数据是新的,但页面是旧的;
updated:Vue已经根据新数据生成新的虚拟DOM,与旧的虚拟DOM做比较,最终完成页面的更新;
beforeDestroy: 当vm.$destroy 被调用时执行,此时vm中所有的data,methods,指令等都是可用的,当对其进行操作并不会引起页面的改变,一般在此阶段进行:关闭定时器,取消订阅,解绑自定义事件等工作;
destroyed: 销毁之后,基本不使用;
常用的生命周期函数:
1.mounted:发送ajax请求,启动定时器,绑定自定义事件,订阅消息等初始化操作;
2.beforeDestroy:清除定时器,解绑自定义事件,取消订阅消息等收尾工作;
关于销毁Vue实例:
1.销毁后借助Vue开发者工具看不到任何信息;
2.销毁后自定义事件会失效,但原生DOM事件依然有效;
3.一般不会在beforeDestroy操作数据,因为即使操作了数据,也不会在触发更新流程了;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="../js/vue.js" type="text/javascript"></script>
<title>生命周期</title>
</head>
<body>
<div class="root">
<h1 :style="{opacity:opacity}">Hello {{name}}</h1>
<h2>当前值是:{{n}}</h2>
<button @click="add">点我n+1</button>
<button @click="bye">点我销毁vm</button>
</div>
<script type="text/javascript">
Vue.config.productionTip = false
new Vue({
el:".root",
data:{
name:'Vue2',
opacity:1,
n:1
},
methods:{
add(a,b,c){
console.log(a,b,c);
this.n++;
},
bye(){
console.log('bye')
this.$destroy();
}
},
beforeCreate(){
console.log("beforeCreate")
},
created(){
console.log("created")
},
beforeMount(){
console.log("beforeMount")
},
mounted(){
this.timer = setInterval(()=>{
this.opacity -= 0.01
if (this.opacity <= 0) this.opacity = 1
},16);
console.log('mounted')
},
beforeUpdate(){
console.log('beforeUpdate')
},
updated(){
console.log('updated')
},
beforeDestroy(){
clearInterval(this.timer)
console.log('beforeDestroy')
},
destroyed(){
console.log('destroyed')
}
})
</script>
</body>
</html>