javascript - v-for 循环中的模数

标签 javascript vue.js vuejs2 v-for

我正在循环中显示 div,并且我想根据循环索引绑定(bind)类。所以我想要实现的是索引 01 具有类 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/

相关文章:

javascript - 选择单选按钮后,如何使用其值动态更新另一个 PHP 变量

javascript - Vuejs渲染错误: "TypeError: Cannot read property ' props' of undefined"Vuejs

javascript - VueJs 2方式数据绑定(bind)更改丢失

javascript - 如何清空以下数组而不导致无限查看此 Vue watch 内?

javascript - 是 <match v-for ='match in matches' v-bind :match ='match' ></match> incorrect? 我可以在同一元素的 v-bind 中使用来自 v-for 的匹配项吗?

javascript - 如何在vue2中的过滤列表中保留项目的引用

javascript - vue-truncate-filter 不过滤并抛出错误

javascript - 设置中的 jquery 数据表对象

javascript - 在 Firefox 插件中注册控制台服务监听器

javascript - 在 TableSorter 中对字符串 'xx,xx€' 进行数字排序