从方法修改监视变量时,使用观察器的 Vue 倒数计时器加速

Vue countdown timer using watcher accelerates when modifying watched variable from method

对 Vue 和 JS 非常陌生。我已经为一个 timerCount 变量(最初设置为 5)设置了一个观察器,它会生成一个 5 秒计时器。当变量达到 0 时,将执行一些代码,我将计时器重置为 5 以重新启动它。这工作得很好,但是,我有一个调用方法的单击事件,该方法将执行不同的代码,然后也将计时器重置为 5,但现在我的计时器已加速(快两倍)。

根据我通过谷歌搜索发现的情况,似乎同时有多个 watcher/timer 个实例 运行,这就是导致速度加快的原因。我该如何解决这个问题,以便我的方法像往常一样简单地重置计时器?

watch: {
    timerCount: {
        handler(value){
            //timer for 5 seconds
            if (value>0){
                setTimeout(() => {
                    this.timerCount--;
                }, 1000);
            }
            //if timer hits 0, execute code and reset timerCount to 5 seconds, this works fine
            else{
                /* Code */
                this.timerCount=5
            }
        },
        immediate: true,
    }
},

methods:{
    //this resets the timer, but it now goes twice as fast, don't know why.
    otherMethod(){
        /* Code */
        this.timerCount=5
    }

}

有什么帮助吗?

这是我得到此代码的 post:

在您的代码中,您正在监视 timerCount。当你对你的 timeCount 进行更改意味着,当你 运行 otherMethod 时,Vue 会再次监视它然后 运行 观察者并再次处理此观察者 运行s。每次你改变 timerCount 变量你的观察者 运行 一次又一次。

实际上,如果没有观察者,您可以使用 setInterval(而不是 setTimeout)在您创建的事件中开始计时。 setInterval 运行 你的代码在给定的时间间隔内,但不是严格的 1000 毫秒。可能是1005ms或更短。

您可以在 setInterval 中创建一些函数并给它 100 毫秒,并控制时间是否超过 5 秒。