Vue2 写一个轮询查询接口数据的方法

1,028 阅读1分钟
  • 要解决的问题,当数据查询较慢导致数据返回过慢,需要多次查询才能取到数据
  • 思路:使用定时器setInterval做轮询处理,数据返回成功清除定时器
data() {
    return {
        timer: null, // 定时器标志
        timeCount: 0, // 查询次数
    }
}
beforeDestory() {
    this.setTimerNull(); // 组件销毁前清空定时器
}
created() {
    this.handlePolling(); // 开启轮询
}
methods: {
    // 终止轮询方法
    handleStopPolling() {
        this.timeCount++;
        if(this.timeCount > 4) {
            this.setTimerNull(); // 轮询超过4次终止
            return true; // 阻止代码继续执行
        } else {
            return false;
        }
    }
}

setTimerNull() {
    clearInterval(this.timer);
    this.timer = null;
}

// 轮询开启
handlePolling() {
    // 查询接口
    this.handleQuery();
    this.timer = setInterval(() => {
        let flag = this.handleStopPolling();
        if(!flag) { // 查询不到4次且数据没返回 继续轮询查询
            this.handleQuery();
        }
    })
}

handleQuery() {
    axios.get('xxx').then(res => {
        if(res.data.leng>0) {
            // 表明接口查询到数据
            this.setTimerNull();
            // TODO 数据处理
        }
    })
}