javascript - vuejs 中的 setTimeout 行为
问题描述
正如您在下面看到的,计时器应该msg
在 90 年代之后更新,但它会立即更新。我知道,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>
推荐阅读
- flutter - Flutter 报错 Column 的子项不能包含任何空值,但在索引 0 处发现了空值
- python - 为什么我使用 sqlalchemy hive 时出现错误?
- ruby-on-rails - 在邮件程序视图中访问虚拟属性 - rails
- php - Laravel Eloquent Query 使用 WHERE 一组条件或 OR 另一组条件以及一些常见条件?
- django - django rest_framework 相对于 AJAX 和 JsonResponce 的优势
- json - JSON 模式条件语句
- html - 如何在带有边框图像和阴影的html5画布上显示完整图像?
- javascript - 如何首先呈现搜索项目和所有匹配项目 JavaScript?
- android - API> 25 中的前台服务在应用程序运行时是否需要通知(可见)
- html - 在网页的一行中打印两个不同的东西