前言:
很多时候,前端页面数据是需要实时数据,目前通信方式主要是https和websocket,如果想通过接口轮询在实现页面数据的定时刷新,那么可以参考下文,如果是websocet,可以参考。
正文:
![](https://img-blog.csdnimg.cn/5b0e5514ea78422692a55213094475ae.png)
首先,定义定时器: 设置定时刷新,五分钟一次:
inverterMonTimer: null,
其次,再所需要定时轮询的接口调用处,进行清除定时器以及数据接收之后的定时处理:
//判断定时刷新是否存在,存在先清除
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
设置定时器:注意:1000代表1s,5分钟是300 * 1000
//设置五分钟一次的定时刷新
this.$nextTick(() => {
this.inverterMonTimer = setInterval(() => {
this.getRealNbqDataListData();
}, 300000); //注意:1000代表1s,5分钟是300 * 1000
});
最后页面钩子函数中,需要清除相应的定时器,避免资源消耗及其其他的问题产生:
activated() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
this.getRealNbqDataListData();
},
deactivated() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
},
beforeDestroy() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
},
全部源码:
![](https://img-blog.csdnimg.cn/14155c52cfad46bb8d263d9f156f2a70.png)
import debounce from "lodash/debounce";
export default {
data() {
return {
page: 1
pageSize: 20,
total: 0,
inverterMonTimer: null, //设置定时刷新,五分钟一次
loading: false,
rouceData: [], //数据接收
}
}
methods: {
//定时刷新列表数据
getRealNbqDataListData: debounce(
function () {
let queryParams = {
page: this.page,
limit: this.pageSize,
};
this.rouceData = [];
this.total = 0;
//判断定时刷新是否存在,存在先清除
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
//已封装列表接口调用(仅供参考,盲目复制会报错!!!)
getRealNbqDataList(queryParams).then(({ data: res }) => {
if (res.code != 0) {
this.$message.config({
maxCount: 1,
});
this.$message.destroy();
return this.$message.error(res.msg);
}
if (res.data.list.length > 0) {
this.total = Number(res.data.total);
for (let item of res.data.list) {
item.eff = item.eff ? item.eff : 0.0;
this.rouceData.push(item);
}
console.log(this.rouceData, "88888");
//设置五分钟一次的定时刷新
this.$nextTick(() => {
this.inverterMonTimer = setInterval(() => {
this.getRealNbqDataListData();
}, 300000);
});
}
}).catch((error) => {
console.log(error);
this.loading = false;
return false;
});
this.loading = true;
},
200,
{ leading: true, trailing: false }
)
},
mounted() {
this.getRealNbqDataListData();
},
activated() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
this.getRealNbqDataListData();
},
deactivated() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
},
beforeDestroy() {
if (this.inverterMonTimer) {
clearInterval(this.inverterMonTimer);
this.inverterMonTimer = null;
}
},
}
在上述代码中,rouceData是一个响应式的数据属性,它将会在每次定时器触发后更新,并且自动更新相关DOM。需要注意的是,在适当的时候,应该在组件销毁时清除定时器,以避免内存泄漏。可以在Vue组件的beforeDestroy等生命周期钩子函数中使用clearInterval函数清除定时器。
总结:
以上就是在Vue中实现接口的定时刷新的一般步骤。当然,具体的实现方式可能会根据你的项目需求和后端接口的设计而有所调整。
|