【问题标题】:Insert item after every nth item in v-for loop在 v-for 循环中的每个第 n 个项目之后插入项目
【发布时间】:2019-02-12 09:53:05
【问题描述】:

我正在遍历产品列表并将它们显示在卡片中。我想在每列出第 18 个产品后展示一次促销:

<div
     v-for="(prod, index) in products"
       :key="index"
       class="w-full md:w-1/3 lg:w-1/4 xl:w-1/4 mb-8 px-2
     >
     <promotion v-if="(index % 18 == 0) && index != 0" ></promotion>
     <product-card v-else :product="prod"></product-card>
</div>

按照我现在写这个的方式,促销被显示,但它被插入到具有匹配索引的项目的位置。如何在不替换的情况下将促销放在第 n 项之前或之后?

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    要保留网格 css,您可以将它们放在 template 下并使用 v-for

    <template v-for="(prod, index) in products">
      <div class="w-full md:w-1/3 lg:w-1/4 xl:w-1/4 mb-8 px-2" 
            v-if="(index % 18 == 0) && index != 0" 
            :key="'promotion-${index}'">
        <promotion></promotion>
      </div>
      <div class="w-full md:w-1/3 lg:w-1/4 xl:w-1/4 mb-8 px-2" 
          :key="'product-${index}'">
        <product-card :product="prod"></product-card>
      </div>
    </template>
    

    【讨论】:

    • 这是完美的。我没有意识到 v-for 可以在模板上使用。谢谢。
    【解决方案2】:

    我认为您只需要在 product-card 元素中删除 v-else 即可

    &lt;product-card :product="prod"&gt;&lt;/product-card&gt;

    【讨论】:

    • 我正在使用 flexbox 并将循环中的每个项目设置为 1/4 行,因此这会导致促销和产品卡显示在 1/4 行空间内
    • 从这里看似乎是一个 css 问题。如果将css放在promotion元素和product-card元素而不是div上会发生什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-02
    • 1970-01-01
    • 2018-06-10
    • 2020-06-18
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多