组件方法轮询解决方案
作用
实现函数的轮询调用
场景
通过轮询调用函数,实现数据定时更新(比如大屏可视化项目)
特点
- 调用后会立即执行函数
- 组件销毁时自动清除定时器
- 单个实例组件支持多个不同的轮询任务
- 支持调用频率间隔的自定义配置
适用版本
vue2.0
使用方法
-
通过Vue.mixin混入
-
调用
import loopQuery from '@/mixins/loopQuery.js'; export default { name: 'App', mixins: [loopQuery], mounted() { this.startLoopQuery(this.getData, 60 * 1000) }, methods: { getData() { // 调用接口,获取响应数据 } } }
源码
export default {
created() {
this._timerMap = new Map();
},
destroyed() {
for (const callback of this._timerMap.keys()) {
this._clearTimer(callback);
}
},
methods: {
// callback 轮询调用的函数
// interval 时间间隔(毫秒,默认30s)
startLoopQuery(callback, interval = 30 * 1000) {
if (typeof callback !== 'function') {
return;
}
this._clearTimer(callback);
const loop = () => {
callback();
this._timerMap.set(callback, setTimeout(loop, interval));
}
loop();
},
_clearTimer(callback) {
if (this._timerMap.has(callback)) {
clearTimeout(this._timerMap.get(callback));
this._timerMap.delete(callback);
}
},
},
}