uniapp,实现每次进入小程序页面后,每五秒轮询一次向接口发送请求,离开页面时停止请求

uniapp,实现每次进入小程序页面后,每五秒轮询一次向接口发送请求,离开页面时停止发送请求

 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 里直接使用。
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值