Vue.js使用setTimeout实现90秒倒计时却立刻更新msg的问题咨询
问题根因分析
你代码的核心问题是语法错误导致条件分支判断失效:
else if(this.countDown === 0);末尾多写了一个多余的半角分号;
这个分号会被JS解析器判定为当前else if分支的逻辑已经结束,后面包裹this.msg赋值语句的大括号是完全独立的代码块,和前面的if、else if判断没有任何绑定关系。所以每次调用timer函数时,不管countDown当前值是多少,都会直接执行修改msg的逻辑,这就是页面刚加载msg就被立刻改写的原因。
修复后代码
JS部分
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) { // 移除了else if末尾的多余分号,赋值逻辑仅在倒计时归0时执行 this.msg = 'You Ran Outta Time!' } } }, created () { this.timer(); }, })
HTML部分(无需修改)
<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>
内容的提问来源于stack exchange,提问作者Vinay
相关产品推荐
相关产品推荐

