gpt4 book ai didi

javascript - 倒数计时器在 vue js 中不起作用弹出

转载 作者:行者123 更新时间:2023-12-04 14:53:37 25 4
gpt4 key购买 nike

我正在尝试在倒计时后重定向到另一个网站。重定向有效,但倒计时仅减少一次。

例如:我已将计数器设置为 5。但是当弹出窗口打开时,它显示 4 并且不会进一步减少。

<p>Redirecting in {{ counter }}</p>
<script>
export default {
name: "modal",
data() {
return {
toggleModal: false,
counter: 5
}
},
methods: {
showModal() {
this.toggleModal = true;
this.countDown();
},
countDown() {
if(this.counter > 0) {
this.counter--;
setTimeout(() => {
window.location.href = 'https://www.google.com';
}, 5000);
}
},
}
};
</script>

最佳答案

基本上您的代码现在正在做的是等待 5 秒并重定向,它重定向的一个副作用是它将倒计时减 1。

您需要做的是递减计数器,每秒递减一次,直到它变为零,然后在您想要进行重定向的下一次计时。

我们首先检查倒计时的时间。如果它高于零,我们要等待一秒钟,然后将计数器减一,然后再次检查。

countDown() {
//If the counter has not reached the end
if(this.counter > 0) {
//Wait 1 second, then decrement the counter
setTimeout(()=>{
this.counter--;
this.countDown();
},1000)
}
else
{
//Count down has reached zero, redirect
window.location.href = 'https://www.google.com';
}
},

关于javascript - 倒数计时器在 vue js 中不起作用弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68598954/

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