javascript - if 语句和 vuejs 重新启动计数器的错误
问题描述
我正在编写一段简单的代码,每次单击特定按钮时都会增加一个计数器,并在达到 3 时重新启动,数字显示在每个按钮中,它似乎工作正常但是我有一个奇怪的错误:如果当您按下任何其他按钮时,第一个按钮未设置为 0,它将第一个按钮重新启动回 0。按钮是否似乎以某种方式链接?
new Vue({
el: "#app",
data: {
one: 0,
two: 0,
three: 0
},
methods: {
chooseOne: function(x, y) {
if ((x == 1) && (this.one < 3)) {
this.one++;
} else {
this.one = 0
}
if (x == 2) {
if ((x == 2) && (this.two < 3)) {
this.two++;
} else {
this.two = 0
}
}
if (x == 3) {
if ((x == 3) && (this.three < 3)) {
this.three++
} else {
this.three = 0
}
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="chooseOne(1,one)">
{{ one }}
</button>
<button @click="chooseOne(2,two)">
{{ two }}
</button>
<button @click="chooseOne(3,three)">
{{ three }}
</button>
</div>
解决方案
你的 if-else 并不一致x
。对于 2 和 3,您有嵌套检查,但对于 1 没有。当 时x = 2
,此条件为假
if ((x == 1) && (this.one < 3))
因此,this.one = 0
每当单击第二个或第三个按钮时都会调用
为 1 添加类似的检查
if (x == 1) {
if (this.one < 3) {
this.one++;
} else {
this.one = 0
}
}
您可以简化代码以像这样传递属性的名称,以避免多次检查
new Vue({
el: "#app",
data: {
one: 0,
two: 0,
three: 0
},
methods: {
chooseOne: function(prop) {
if (this[prop] < 3) {
this[prop]++
} else {
this[prop] = 0
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button @click="chooseOne('one')">
{{ one }}
</button>
<button @click="chooseOne('two')">
{{ two }}
</button>
<button @click="chooseOne('three')">
{{ three }}
</button>
</div>
推荐阅读
- node.js - Heroku Nodejs vs Vercel Nodejs
- c# - 在同一个地方打印数字
- .net-core - .NET Core 运行状况检查:找不到所需的服务
- vba - 基于另一列值的 VBA Subtotal(9,"range")
- c# - 如何从 Web API 调用 ASP.NET Core Web MVC
- c# - 2sxc 获取实体的字段列表
- python - 装饰器的类型注释
- asp.net-core - 无法通过 Envoy (v1.17.0) 将 API 调用转发到 docker-compose (v1.27.4) 内的各自路由
- flutter - 未布置 RenderBox - 具有动态子项的特殊情况
- discord - discord.js \n 转义字符在使用 setDescription 的嵌入中不起作用