You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js 弹窗中倒计时器仅递减一次无法正常运行如何解决?

问题原因

你的倒计时逻辑存在两个核心错误:

  • countDown 方法仅在弹窗打开时被调用1次,没有设置循环调用的逻辑,因此counter只会执行1次递减操作就停止
  • 跳转用的setTimeout在第一次counter递减后就直接注册,倒计时的数值变化和跳转逻辑完全没有关联,无论counter是否走完,5秒后都会触发跳转
修复方案

调整倒计时逻辑,每次counter递减后如果数值仍大于0,就设置1秒后再次调用countDown方法,直到counter减到0时再触发跳转。同时新增定时器存储字段,避免内存泄漏。

修改后的完整代码如下:

<p>Redirecting in {{ counter }}</p>
export default {
    name: "modal",
    data() {
        return {
            toggleModal: false,
            counter: 5,
            redirectTimer: null // 存储定时器ID,用于后续清理
        }
    },
    // 组件销毁前清理定时器,避免内存泄漏
    // Vue3 请将钩子名改为 beforeUnmount
    beforeDestroy() {
        if(this.redirectTimer) clearTimeout(this.redirectTimer)
    },
    methods: {
        showModal() {
            this.toggleModal = true;
            this.countDown();
        },
        countDown() {
            // 每次执行前清空旧定时器,避免重复触发
            if(this.redirectTimer) clearTimeout(this.redirectTimer)
            if(this.counter > 0) {
                this.counter--;
                // 1秒后再次执行倒计时
                this.redirectTimer = setTimeout(() => {
                    this.countDown()
                }, 1000)
            } else {
                // 倒计时归0后再执行跳转
                window.location.href = '你的目标跳转地址'
            }
        },
    }
};

内容的提问来源于stack exchange,提问作者Reman Bala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 05:57:03