Vue.JS倒计时不工作

Vue.JS countdown not works

本文关键字:工作 倒计时 JS Vue      更新时间:2023-09-26

我有一个价值的应用程序,但倒计时不工作好。其实我也不知道为什么。

查看{{ $parent.timer }} i see good value.

Vue data:

data: function() {
      return {
         timer : 3,
...

,这是我的倒计时功能:

countdown : function(time,callback)
    {
         //time is equal 5
        this.timer = time;
        //this.timer is equal 5
        var timerInterval = undefined;
        timerInterval = setInterval(function() {
            if(this.timer == 1) {
                this.timer = 0;
                callback();
                return clearInterval(timerInterval);
            }
            // First time undefined, in 2nd is NaN
            this.timer -= 1;
            // NaN
        }, 1000);
    }

调用函数:

this.countdown(data.time,function(){ //smtng });

我做错了什么?

我希望有人能帮助我:)非常感谢!

这是this范围的问题,如下所述:

function() {...}在内部创建一个新的作用域。如果在这个函数中使用this,它就不指向外部作用域。因此,Vue组件的this.timer不会从setInterval()内部得到更新。

() => {...}像函数一样工作,但不创建一个新的作用域。

检查以下代码是否有效:

timerInterval = setInterval(() => {
    if(this.timer == 1) {
        this.timer = 0;  // `this` points to the scope of Vue component
        callback();
        // ...
    }
    // ...
}, 1000);

关于箭头函数的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions