简体   繁体   English

Vue.JS倒数计时不起作用

[英]Vue.JS countdown not works

I have a vue application, but the countdown not work good. 我有一个Vue应用程序,但倒计时效果不好。 Actually i dont know why. 其实我不知道为什么。

View {{ $parent.timer }} i see the good value. 查看{{ $parent.timer }}我看到了很好的价值。

Vue data: Vue资料:

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

and here is my countdown function: 这是我的倒数功能:

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);
    }

call function: 通话功能:

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

What i do bad? 我做的不好吗? Its work in my older Vue application. 它在我较旧的Vue应用程序中起作用。

I hope someone can help to me :) Thanks so much! 我希望有人可以帮助我:)非常感谢!

It is an issue with scope of this , as explained below: 这是this范围的问题,如下所述:

function() {...} creates a new scope inside. function() {...}创建一个新范围。 If you use this inside this function, it does not refer to outer scope. 如果在此函数内部使用this函数,则不会引用外部作用域。 Therefore your this.timer of Vue component does not get updated from inside your setInterval() . 因此,不会从setInterval()内部更新Vue组件的this.timer

() => {...} works like a function but does not create a new scope inside. () => {...}作用类似于一个函数,但不会在其中创建新的作用域。

Check if the following code works: 检查以下代码是否有效:

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

More info on arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions 有关箭头功能的更多信息: https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM