[英]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.