【问题标题】:Vue.JS countdown not worksVue.JS 倒计时不起作用
【发布时间】:2017-03-05 04:44:45
【问题描述】:

我有一个 vue 应用程序,但是倒计时不能正常工作。 其实我也不知道为什么。

查看{{ $parent.timer }}我觉得物超所值。

Vue 数据:

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

我做错了什么?它在我的旧 Vue 应用程序中工作。

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

【问题讨论】:

  • 使用setInterval(() => { ... },这样你的this就是你想要的范围。

标签: javascript vue.js


【解决方案1】:

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

function() {...} 在内部创建一个新范围。如果你在这个函数中使用this,它并不指向外部作用域。因此,您的 this.timer 的 Vue 组件不会从您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    相关资源
    最近更新 更多