我正在循环中显示 div,并且我想根据循环索引绑定(bind)类。所以我想要实现的是索引 0
和 1
具有类 col-6
然后是 2,3,4
有索引 col-4
,然后 5 和 6 有类 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 返回“col-6”,为 2、3、4 返回“col-4”,并且由于它使用 moduo
,因此对 5、6 返回“col-6' 和 7、8、9 返回 'col-4' 等等
关于javascript - v-for 循环中的模数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53116617/