vue中数据状态轮询
1、数据接口和状态接口是分开的
首先在页面挂在后请求数据,然后判断数据中状态是否有需要轮询的,有的话就轮询:
javascript
async getTableDataList() {
this.tableLoading = true;
try {
let params = {
page: this.dataPage,
page_size: this.dataPagesize,
}
const res = await this.$axios.get(`url`, { params });
if (res.data.code == 200) {
this.tableLoading = false;
this.dataTableData = res.data.data;
this.dataTotalNumber = res.data.paging.total;
let isExistAnalyzing = this.dataTableData.find((item) => {
if (item.status == 1) {
return item;
}
});
//如果存在分析中的数据
if (isExistAnalyzing) {
this.pollStatus();
} else {
this.endPollStatus()
}
} else {
this.tableLoading = false;
this.dataTableData = [];
}
} catch (err) {
console.log(err);
}
},
要在data中定义定时器:
javascript
data() {
return {
pollStatusTimer: null,
}
}
轮询和结束轮询一级状态接口如下:
javascript
pollStatus() {
this.endPollStatus(this.pollStatusTimer);//防止有未清除的定时器
this.pollStatusTimer = setTimeout(() => {
this.getDatasetStatus();
}, 3000);
},
endPollStatus() {
clearTimeout(this.pollStatusTimer);
},
async getDatasetStatus() {
const res = await this.$axios.get(
`url`
);
if (res.data.code == 200) {
let statusList = res.data.data;
this.dataTableData.forEach((item) => {
statusList.forEach((el) => {
if (item.id == el.id) {
item.status = el.status;
item.studyCount = el.studyCount;
item.progress = el.progress == null ? 0 : Number(el.progress);
}
});
});
let incomplete = statusList.find((item) => {
if (item.status == 1) {
return item;
}
});
if (incomplete) {
this.pollStatus();
} else {
this.endPollStatus();
}
}
},
最后,要在组件销毁前清空定时器,防止内存泄漏
2、无单独的状态接口
如果没有单独的状态接口,把状态方法getDatasetStatus换成数据方法getTableDataList即可