[英]setTimeout behaviour in vuejs
正如您在下面看到的,計時器應該在 90 秒后更新msg
,但它會立即更新。 我知道setInterval
和watch
但我需要知道為什么代碼不起作用
我們所做的就是檢查計數器是否高於 0,如果這樣會產生另一個超時,並觸發當前函數等等
var view = new Vue({ el: '#app', data: { countDown: 90, msg: "There's still time.." }, methods: { timer: function () { if (this.countDown > 0) { setTimeout(() => { this.countDown-- this.timer() }, 1000); } else if(this.countDown === 0); { this.msg = 'You Ran Outta Time!' } } }, created () { this.timer(); }, })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Vue test</title> </head> <body> <div id="app"> <h2>{{msg}}</h2> </div> </body> </html>
刪除;
在else if(this.countDown === 0)
被視為語句之后,因此您的代碼與以下內容相同:
if (this.countDown > 0) {
setTimeout(() => {
this.countDown--
console.log(this.countDown)
this.timer()
}, 1000);
}
else if(this.countDown === 0)
{
}
this.msg = 'You Ran Outta Time!'
var view = new Vue({ el: '#app', data: { countDown: 90, msg: "There's still time.." }, methods: { timer: function () { if (this.countDown > 0) { setTimeout(() => { this.countDown-- console.log(this.countDown) this.timer() }, 1000); } else if(this.countDown === 0) { this.msg = 'You Ran Outta Time!' } } }, created () { this.timer(); }, })
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>Vue test</title> </head> <body> <div id="app"> <h2>{{msg}}</h2> </div> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.