我正在编写一段简单的代码,每次单击特定按钮时都会增加一个计数器,并在达到 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
时,此条件为 false
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>
关于javascript - if 语句和 vuejs 重启计数器的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56830071/