Javascript Vue.JS倒计时不起作用

Javascript Vue.JS倒计时不起作用,javascript,vue.js,Javascript,Vue.js,我有一个vue应用程序,但倒计时效果不好。 其实我不知道为什么 查看{{$parent.timer}我看到了好的值 Vue数据: data: function() { return { timer : 3, ... 这是我的倒计时功能: countdown : function(time,callback) { //time is equal 5 this.timer = time; //this.time

我有一个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 });
调用函数:

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应用程序中工作

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

这是本范围内的一个问题,如下所述:

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

()=>{…}
的工作原理类似于函数,但不会在其中创建新的作用域

检查以下代码是否有效:

timerInterval=setInterval(()=>{
如果(this.timer==1){
this.timer=0;//`this`指向Vue组件的范围
回调();
// ...
}
// ...
}, 1000);
有关箭头函数的更多信息:

使用
setInterval(()=>{…}
,以便您的
是您想要的范围。