Vue JS Computed 属性 返回错误的输出

Vue JS Computed property returning wrong output

我被困在 Vue JS 上交给我的任务上,不知道这段代码出了什么问题。

任务正在生成动态 table,其中包含 5 列背景颜色和 4 种颜色,即红色、蓝色、黄色、绿色。当列循环到达第 5 列时,应在其上放置红色背景色,下一行继续使用蓝色、黄色、绿色、红色。

new Vue({
  el: '#app',
  data: {
    tableRows: ['Table Row 1'],
    counter: 1,
    bgColor: ['red', 'blue', 'yellow', 'green'],
    fontSize: '30',
    colNumber: 0,
    maxColumn: 5,
  },

  computed: {
    bgColorComputed: function() {

      if (this.colNumber == 4) {
        this.colNumber = 0;
        return this.bgColor[this.colNumber];
      }

      return this.bgColor[this.colNumber];
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <table border="1" width="500px" height="300px">
    <tr v-for="(content, index) in tableRows">
      <td v-for="colorIndex in maxColumn" :style="{ backgroundColor: bgColorComputed }"> 
        bgColorComputed : {{ bgColorComputed }} <br> <br> 
        row count {{ counter }} <br> 
        column count {{ colNumber = colorIndex - 1 }}
      </td>
    </tr>
  </table>
</div>

此代码的输出是:Red,Red,Blue,Yellow,Green 而不是 Red,Blue,Yellow,Green,Red。

为什么返回的 computedBgColor 是红色、蓝色、黄色、绿色,红色出现两次?

已缓存计算属性。您正在尝试使用单个 bgColorComputed 属性 来同时表示许多不同的颜色。这不是它的用途。

相反,您可以将代码移动到一个方法中,然后多次调用该方法(每列一次)。

其他问题:

  • 您跟踪索引的方式不可靠。 与其将 if (this.colNumber == 4) 作为特例检查,不如使用 mod 运算符 this.bgColor[colorIndex % this.bgColor.length]。这适用于任何列,而不仅仅是 4.

  • 您的初始列索引设置为零。然后稍后您使用 v-for="colorIndex in maxColumn" (从 1 开始)然后 {{ colNumber = colorIndex - 1 }} 更新它,这再次将 colNumber 设置回零。这就是为什么您得到两个红色列的原因。这是不必要的。理想情况下,您应该避免在视图模板中改变状态,这样您就不会 运行 陷入这些不一致问题。

new Vue({
  el: '#app',
  data: {
    tableRows: ['Table Row 1'],
    counter: 1,
    bgColor: ['green', 'red', 'blue', 'yellow',],
    fontSize: '30',
    colNumber: 0,
    maxColumn: 5,
  },

  methods: {
    getBgColor: function(colorIndex) {
      return this.bgColor[colorIndex % this.bgColor.length];
    }
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<div id="app">
  <table border="1" width="500px" height="300px">
    <tr v-for="(content, index) in tableRows">
      <td v-for="colorIndex in maxColumn" 
  :style="{ backgroundColor: getBgColor(colorIndex) }">
  getBgColor : {{ getBgColor(colorIndex) }} <br> <br> 
  row count {{ counter }} <br> 
  column count {{ colNumber = colorIndex - 1 }}
   </td>
    </tr>
  </table>
</div>