需求:每次进入指定页面后,每隔5分钟自动刷新列表数据,代码如下
created() {
this.periodicRefresh()
},
methods:{
//查询当前出票中数据
getTicketData(){
console.log("定时器"+this.timer);
let res = {
per_page: this.per_page, //不传默认25
page: this.nowPages,
type: 2,
query_start_time: "",
query_end_time: "",
oid: "",
mobile: "",
pin_search: "",
cinema_set:1,
};
get_movie(res).then((response) => {
if(response.code==200){
this.ticketData = response.data.count;
}
}).catch((err) => {});
},
//定时刷新列表
periodicRefresh(){
this.getTicketData()
clearInterval(this.timer)
this.timer=setInterval(this.getTicketData,300000)
},
}
问题:当项目跳转另外一个页面,再次回到当前页面时,会产生多个定时器,导致列表刷新时间越来越近
原因:setInterval属于全局方法,当我们停在当前页面时,会产生一个定时器,从其他页面再次回到当前页面时,会再次产生定时器,而之前的定时器,实际上并没有被销毁(虽然在定时器之前调用了清除方法,而实际上,页面刷新回来时,this.timer 是"",因为this.timer属于当前页面的变量,而已经产生的定时器是全局变量,所以并没有清理掉已经产生的定时器)
//定时刷新列表
periodicRefresh(){
this.getTicketData()
clearInterval(this.timer)//这里虽然在定时器之前调用了清除方法,而实际上,页面刷新回来时,this.timer 是"",因为this.timer属于当前页面的变量,而已经产生的定时器是全局变量,所以并没有清理掉已经产生的定时器
this.timer=setInterval(this.getTicketData,300000)
},
所以,修改代码如下,至此问题解决
created() {
this.periodicRefresh()
},
beforeDestroy(){
console.log("销毁定时器"+this.timer);
clearInterval(this.timer)
},
methods:{
//查询当前出票中数据
getTicketData(){
console.log("定时器"+this.timer);
let res = {
per_page: this.per_page, //不传默认25
page: this.nowPages,
type: 2,
query_start_time: "",
query_end_time: "",
oid: "",
mobile: "",
pin_search: "",
cinema_set:1,
};
get_movie(res).then((response) => {
if(response.code==200){
this.ticketData = response.data.count;
}
})
.catch((err) => {});
},
//定时刷新列表
periodicRefresh(){
this.getTicketData()
this.timer=setInterval(this.getTicketData,300000)
},
}