我正在使用moment js
将时间倒计时为10,9,8,7,6。它成功倒计时了console.log
上的时间,但我无法将其作为数据传递。
下面是我在jsfiddle上的代码
将setInterval
内部的功能更改为箭头功能,以便将this
读取为Vue组件:
setInterval(() => {
duration.subtract(interval, "milliseconds"); //using momentjs substract function
this.countdownTimer = moment(duration.asMilliseconds()).format('s');
console.log(moment(duration.asMilliseconds()).format('s'));
/* countdown timer works for console.log */
}, interval );
这是因为默认情况下setInterval处理程序中的this
指向窗口对象。您可以通过在函数中添加.bind(this)
来更改此设置。更新JSFiddle:https://jsfiddle.net/qg4863tv
在此了解更多信息:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval(查找The "this" problem
)