vue2中的组件生命周期

组件生命周期

常见应用

不要死记硬背,要根据具体情况灵活处理

加载远程数据

1
2
3
4
5
6
7
8
9
10
export default {
data(){
return {
news: []
}
},
async created(){
this.news = await getNews();
}
}

直接操作DOM

1
2
3
4
5
6
7
8
9
10
11
12
export default {
data(){
return {
containerWidth:0,
containerHeight:0
}
},
mounted(){
this.containerWidth = this.$refs.container.clientWidth;
this.containerHeight = this.$refs.container.containerHeight;
}
}

启动和清除计时器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
export default {
data(){
return {
timer: null
}
},
created(){
this.timer = setInterval(()=>{
...
}, 1000)
},
destroyed(){
clearInterval(this.timer);
}
}