v-for 循环中的模数

Modulo in v-for loop

我在循环中显示 div,我想根据循环索引绑定 class。所以我想要实现的是索引 01 有 class col-6 然后 2,3,4 有索引 col-4 然后 5 和 6 有class col-6 等等。

所以最后我的 div 看起来像这样:

div.col-6 div.col-6
div.col-4 div.col-4 div.col-4
div.col-6 div.col-6
div.col-4 div.col-4 div.col-4
div.col-6 div.col-6

等等..

我找不到执行此操作的模式我尝试使用模数但运气不好。目前我的代码是:

<div v-for="(n, index) in imagesArr" :class="index === 0 || index === 1 ? 'col-6' : 'col-4'" style="padding: .5rem">
    <img :src="n" :alt="'Zdjęcie jachtu nr ' + index" class="img-fluid">
</div>

当然,我可以像上面那样检查每个索引,但它看起来很糟糕,因为这个循环很长,所以我正在寻找另一种方法。

我建议创建计算 属性

computed: {    
    classNameByIndex: function (index) {
      return index % 5 == (0 || 1) ? 'col-6' : 'col-4';
    }
  }

这将用于 0、1 return 'col-6' 和 2、3、4 return 'col-4' 并且因为它使用 moduo 它会做同样适用于 5、6 return 'col-6' 和 7、8、9 return 'col-4' 等等