首页 > 解决方案 > 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>

标签: javascriptif-statementvue.js

解决方案


你的 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>


推荐阅读