[英]Vue.JS countdown not works
我有一个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应用程序中起作用。
我希望有人可以帮助我:)非常感谢!
这是this
范围的问题,如下所述:
function() {...}
创建一个新范围。 如果在此函数内部使用this
函数,则不会引用外部作用域。 因此,不会从setInterval()
内部更新Vue组件的this.timer
。
() => {...}
作用类似于一个函数,但不会在其中创建新的作用域。
检查以下代码是否有效:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.