Vue的生命周期
Vue的概念
组件在创建到销毁会经历一些列的过程,称为生命周期,在过程中执行的回调函数称为周期钩子函数
Vue生命周期的作用
可以让我们在恰当时期,做一些自动操作,网络请求数据,监听dom数据,执行定时器,清除定时器,结束监听
生命周期
总结下来一共8个:创建前后(beforeCreated、created),挂载前后(beforeMount、mounted),更新前后(beforeUpdate、updated),销毁前后(beforeDestroy、destroyed)
其中比较重要的有3个:创建后,挂载后,销毁前
作用:(重要)
- 创建后(created):ajax请求,本地数据读取,window事件监听,定时器开启
- 挂载后(mounted):可以和created重复,可以操作dom
- 销毁前(beforeDestroy):移除事件监听,清除定时器
beforeCreate() {
console.log("beforeCreate 创建前", this, this.msg);
},
//创建完毕,已经有this,有数据
//作用:执行ajax,读取本地数据,开启定时器,注册事件window相关
created() {
console.log("*created 创建前", this, this.msg);
console.log("*created 创建前", this.$el);
},
//挂载前,生成了dom没有编译(挂载)
beforeMount() {
console.log("beforeMount 挂载前", this.$el);
console.log("beforeMount 挂载前", document.querySelector("#app").innerHTML);
},
//挂载完毕,dom已经被挂载到真实的节点,已经完成了编译工作
//作用:执行ajax,读取本地数据,开启定时器,注册事件,操作dom节点
mounted() {
console.log("mounted 挂载后", document.