生命周期
- 又名:生命周期回调函数,生命周期函数,生命周期钩子(程序员间沟通常称生命周期钩子)。
- 是什么:Vue在关键时刻帮我们调用的一些特殊名称的函数。
- 生命周期函数的名字不可更改,但是函数的具体内容是程序员根据需求编写的。
- 生命周期函数中的 this 指向是 实例 或 组件实例对象。
流程图解析
八个生命周期:
1.beforeCreate ------------>创建数据检测、数据代理之前
2.create ---------------------->创建数据检测、数据代理
3.beforeMount------------->挂载之前
4.mounted------------------>挂载完毕
[重要钩子]
5.beforeUpdate------------>更新之前
6.updated------------------->更新完毕
7.beforeDestroy----------->销毁之前
[重要钩子]
8.destroyed---------------->销毁完毕
还有三个生命周期在图中没有体现,因为只在路由中使用
实例
<div id="root">
<h2 :style="{opacity :opacity}">当前的n值是:{{n}}</h2>
<button @click="add">点击+1</button>
<button @click="stop">点击停止</button>
</div>
new Vue({
el: '#root',
data() {
return {
n: 1,
opacity: 1,
};
},
methods: {
stop() {
//想要使用其他函数里的东西,可以将其绑定在 this 上
clearInterval(this.timer);
},
add() {
this.n++;
},
},
// Vue完成模板解析并把'初始的'真实DOM元素放入页面后(挂载完毕)调用(只会调用一次)
mounted() {
//绑定给this
this.timer = setInterval(() => {
this.opacity -= 0.01;
if (this.opacity <= 0) {
this.opacity = 1;
}
}, 16);
},
});
</script>
常用的生命周期钩子:
- mounted:发送ajax请求、启动定时器、绑定自定义事件、订阅消息等【初始化操作】。
- beforeDestroy:清除定时器、解绑自定义事件、取消订阅消息等【收尾工作】。
关于销毁Vue实例:
- 销毁后借助Vue开发者工具看不到任何信息。
- 销毁后自定义事件会失效,但原生DOM事件仍然有效
- 一般不会再beforeDestroy操作数据,因为即便操作数据,也不会触发更新流程了。