在v-for循环的某个索引上添加一个空div

时间:2020-05-30 14:45:37

标签: javascript vue.js nuxt.js

我正在通过计算变量将一系列产品项传递到收集页面上的收集项组件中。在第三种产品之后,我希望有一个空的收藏品,即。收集项目模板,但其中没有产品内容。如果有人对我如何在Vue.js中实现这一目标有任何想法,我将不胜感激。

    SimpleDateFormat sdffecha_modif = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    String fechaModif = sdffecha_modif.format(new Date());

2 个答案:

答案 0 :(得分:0)

您可以将<collection-item包装在模板中,并进行v-for循环,然后在您的v-if上添加一个collection-item条件

<template>
  <section>
    <template v-for="(row, index) in rows">
      <collection v-if="index !== 3" :key="index"></collection>
      <div v-else :key="index">something else if needed or remove</div>
    </template>
  </section>
</template>

codesandbox:

https://codesandbox.io/s/cocky-wood-qglqe?file=/pages/index.vue:0-216

答案 1 :(得分:0)

如果您知道它永远是您想要此空项目之后的第三种产品,则可以在外部容器(例如templatewhich acts as an invisible wrapper element in Vue)而不是collection-item上循环,并结合使用v-ifindex property available from v-for(链接的Vue文档中的第二个示例)。

<template v-for="(product, index) in products">
    <collection-item :collection-item="product" />
    <collection-item v-if="index == 2" />
</template>

或者,您可以以编程方式在第三个位置将空产品拼接到数组中,这最终会得到相同的结果,但是如果纯粹出于视觉原因,可能不如将其添加到模板中那样清晰。

最后一点,每当在自定义组件上使用v-for时,您都必须 (自Vue v2.2.0起)包括一个key属性,以帮助Vue区分列表它呈现的元素。这应该是所有元素(例如product.id)所特有的,但是index也可以作为万不得已的方法,只要它不会引起问题。