V
V
Vadim2018-06-01 16:50:12
Vue.js
Vadim, 2018-06-01 16:50:12

How to alternate components in a Vue JS loop?

I'm doing a simple example, like here , only on Vue. The objects (products) in the array have a category property. The array is rendered into a table. In the table, the category line goes first, and then the products of this category themselves (this array is already sorted). The markup for the ProductTable component looks like this:

<template>
  <table>
    <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
    </tr>
    </thead>
    <tbody>
      <ProductRow
              v-for="product in filteredProducts"
              :key="product.id"
              :item="product"
      />
    </tbody>
  </table>
</template>

How to make sure that where there is no previous element (the first iteration of the loop) and where the category of the previous element was different, the ProductCategoryRow component is inserted first and after the ProductRow?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim, 2018-06-01
@vadimek

I did, but it may not be the best option:

<template>
  <table>
    <thead>
    <tr>
      <th>Name</th>
      <th>Price</th>
    </tr>
    </thead>
    <tbody>
      <template v-for="(product, index) in filteredProducts">
        <ProductCategoryRow
                v-if="index == 0 || product.category != filteredProducts[index - 1].category"
                :category="product.category"
        />
        <ProductRow
                :key="product.id"
                :item="product"
        />
      </template>
    </tbody>
  </table>
</template>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question