我有一个简单的组件,可以从API提取数据,我想添加一个进度条来指示下一次数据刷新。 API的调用间隔为10秒,并且数据本身通常每分钟刷新一次。
进度栏的值基于日期:2018-12-04T16:10:09.508367Z
,其中我使用moment
库:moment().diff(2018-12-04T16:10:09.508367Z, 'seconds')
因为这可能是一个随机值,所以进度条的步长不相等,并且它们并非从完整的条开始。
我想知道是否有办法改善这一点?
这是我在codeandbox上的伪code,以说明这一点。
<template>
<b-container fluid>
<b-row>
<b-col md="12" class="p-0 fixed-top">
<b-progress
:value="progressCounter"
:max="progressMax"
height="5px"
variant="warning"
>
</b-progress>
</b-col>
</b-row>
<b-row>
<b-col md="12" class="">
{{ progressMax }} / {{ progressCounter }}
</b-col>
</b-row>
</b-container>
</template>
<script>
export default {
name: "ProgressBar",
data() {
return {
progressCounter: 60,
progressMax: 60,
interval: null,
refresh: 10000,
time: 0
};
},
methods: {
getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
},
progress() {
/*
this.time is just a pseudo code here, the real progressCounter is recived from
an API call and seconds are calculated by deducting time from now:
this.progressCounter = 60 - moment().diff(created, 'seconds')
"created" comes from an API call and it's refreshed (~) every minute
*/
if (this.time <= 10) {
this.time = this.getRandomInt(40, 59);
} else {
this.time -= 10;
}
this.progressCounter = this.time;
console.log(
`this.time: ${this.time}, this.progressCounter: ${this.progressCounter}`
);
}
},
mounted() {
this.interval = setInterval(
function() {
this.progress();
}.bind(this),
this.refresh
);
},
beforeDestroy() {
clearInterval(this.interval);
}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped></style>