gpt4 book ai didi

javascript - vue倒计时器无限循环

转载 作者:行者123 更新时间:2023-11-28 03:23:48 25 4
gpt4 key购买 nike

嗨,我正在尝试使用倒计时器,但尽管这有效,但每次运行时我都会收到控制台错误,提示“您在组件渲染函数中可能有无限更新循环。”所以必须需要调整一些东西

export default {
data: () => ({
timeDiff: 0,
time: {
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
},
}),
created(){
this.countdown();
},
methods: {
countdown() {
setTimeout(() => {
if (this.$store.state.allDataLoaded) {
var countDownDate = new Date('December 17, 2019 03:24:00');
var now = new Date();
this.timeDiff = countDownDate - now;
this.time.days = Math.floor(this.timeDiff / (1000 * 60 * 60 * 24));
this.time.hours = Math.floor((this.timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
this.time.minutes = Math.floor((this.timeDiff % (1000 * 60 * 60)) / (1000 * 60));
this.time.seconds = Math.floor((this.timeDiff % (1000 * 60)) / 1000);
} else {
this.timeDiff = -1;
this.time.days = 0;
this.time.hours = 0;
this.time.minutes = 0;
this.time.seconds = 0;
}
this.countdown()
}, 1000)
},
},
computed: {
timeDiffComp(){
return this.timeDiff
},
timeComp(){
return this.time
},
}
};

最佳答案

var application = new Vue({
template: '<div>{{ remaining.days }} days, {{ remaining.hours }} hours, {{ remaining.minutes }} mins, {{ remaining.seconds }} sec</div>',
data:
{
counter: 0,
countdown: new Date('2019-12-17T03:24:00Z')
},
created: function()
{
this.advance();
},
methods:
{
advance: function()
{
setTimeout(this.timer, 1000);
},
timer: function()
{
this.counter++;
this.advance();
}
},
computed:
{
remaining: function()
{
var tmp = this.counter + 1; // we just want to invalidate the cached computed value and thus trigger re-rendering of the template
var timeDiff = this.countdown.getTime() - Date.now();
return {
days: Math.floor(timeDiff / (1000 * 60 * 60 * 24)),
hours: Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
minutes: Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60)),
seconds: Math.floor((timeDiff % (1000 * 60)) / 1000),
}
}
},
}).$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

关于javascript - vue倒计时器无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58862910/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com