本文介绍了Vue.JS 倒计时不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 vue 应用程序,但倒计时效果不佳.其实我也不知道为什么.

I have a vue application, but the countdown not work good.Actually i dont know why.

查看 {{ $parent.timer }} 我看到了很好的价值.

View {{ $parent.timer }} i see the good value.

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 应用程序.

What i do bad? Its work in my older Vue application.

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

I hope someone can help to me :)Thanks so much!

推荐答案

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

It is an issue with scope of this, as explained below:

function() {...} 在里面创建一个新的作用域.如果你在这个函数内部使用 this ,它不会引用外部作用域.因此,您的 this.timer Vue 组件不会从 setInterval() 内部更新.

function() {...} creates a new scope inside. If you use this inside this function, it does not refer to outer scope. Therefore your this.timer of Vue component does not get updated from inside your setInterval().

() =>{...} 像函数一样工作,但不会在内部创建新的作用域.

() => {...} 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);

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

More info on arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions

这篇关于Vue.JS 倒计时不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 17:27