data() {
return {
timer: null
}
},
methods: {
async getBrowseAddRecord() {
let res = await getBrowseAddRecord({ //定义好的请求接口方法
browseType: 0,
browseId: this.$store.state.currentCustManagerId,
});
},
}
onShow() {
if(this.$store.state.token) {
this.getBrowseAddRecord();
this.timer = setInterval(this.getBrowseAddRecord, 5000);
}
}
// 网上搜集到的轮询方法大方向上是有用的,但在uniapp小程序页面中,还是遇到了:
// 跳出页面后,轮询依然在运行的情况。对此解决方法如下:
// onUnload,onHide,destroyed 中都要对timer进行销毁;
// 清除 timer 之前,先做是否存在的判断,避免报错;清除后对 timer 多做一步置空的操作
onUnload() {
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
onHide() {
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
},
destroyed() {
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
特别需要注意的是,在页面中有分享海报之类的点击操作,轮询若停止发送请求,
要检查轮询请求是否写在了 onShow 生命周期里(需要写在 onShow 里);若有传值需求,可在 onLoad生命周期里拿到传入参数,在 onShow 里直接使用。