【问题标题】:Countdown timer not working in vue js pop up倒数计时器在vue js中不起作用弹出
【发布时间】:2021-10-06 11:17:53
【问题描述】:

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

例如: 我已将计数器设置为 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>

【问题讨论】:

  • 欢迎来到stackoverflow
  • setTimeout(() =&gt; { window.location.href = 'https://www.google.com'; }, this.counter * 1000); 也许?

标签: javascript vue.js vuejs2 vue-component vuetify.js


【解决方案1】:

基本上你的代码现在正在做的是等待 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';
    }
},

【讨论】:

  • 我已将其标记为最佳答案。由于这是我的新帐户,我不知道我的投票是否已显示。无论如何,感谢您的时间和精力。
猜你喜欢
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多