组件生命周期
常见应用
不要死记硬背,要根据具体情况灵活处理
加载远程数据
export default {
data(){
return {
news: []
}
},
async created(){
this.news = await getNews();
}
}
为什么加载远程数据不在更早的beforeCreate呢,是因为获取网络数据可能需要参数,而这些参数有可能是放在data里面,只有注入完成之后才可以使用this.属性去获取。所以一般我们是放在create这个里面,当然如果你不需要什么参数,放在beforeCreate也是没有任何问题。
直接操作DOM
export default {
data(){
return {
containerWidth:0,
containerHeight:0
}
},
mounted(){
this.containerWidth = this.$refs.container.clientWidth;
this.containerHeight = this.$refs.container.containerHeight;
}
}
这里要从dom里面获取一些信息,当然需要在生成真正的dom之后,所以需要在mounted里面。
启动和清除计时器
export default {
data(){
return {
timer: null
}
},
created(){
this.timer = setInterval(()=>{
...
}, 1000)
},
destroyed(){
clearInterval(this.timer);
}
}
dom 已经销毁了,定时器也不需要了,所以放在这里。