【问题标题】:Modulo in v-for loopv-for 循环中的取模
【发布时间】:2019-04-06 13:59:15
【问题描述】:

我在循环中显示 div,我想根据循环索引绑定类。所以我想要实现的是索引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>

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

【问题讨论】:

    标签: javascript vue.js vuejs2 v-for


    【解决方案1】:

    我建议创建计算属性

    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' 等等

    【讨论】:

    • 你可以缩短代码 { return index % 5 == 0 || 1 ? 'col-6' : 'col-4'}
    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 2020-04-01
    • 2019-02-04
    • 1970-01-01
    • 2021-02-09
    • 1970-01-01
    • 2018-04-06
    相关资源
    最近更新 更多