javascript - if 语句和 vuejs 重启计数器的错误

标签 javascript if-statement vue.js

我正在编写一段简单的代码,每次单击特定按钮时都会增加一个计数器,并在达到 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/

相关文章:

javascript - Ajax 调用被跳过

c - 在 getch() 之后,即使在输入 1-6 之后,程序也会忽略 if。

javascript - 编写一个接受正整数 N 并返回 N 的函数

javascript - 在 Javascript 中通过多个 if 语句运行 While 循环

node.js - 为什么对 Babel 和 ESLint 使用 Vue CLI?

javascript - Vue.js:如何读取计算函数中的 $index ?

html - Vue.js Markdown 过滤器

Javascript 生成的输入字段未发布

javascript - 创建JS : Get the ACTUAL bound area after the object has been rotated

Javascript - 完成输入后调用函数