Search code examples
javascriptfirebase-realtime-databasevuejs2v-for

How to do a nested v-for with data from two seperate Firebase collections


I have two Firebase collections: Categories and Products.

My data schema looks like this:

categories: {
  categoryId1: {
    name: Category1
  },
  categoryId2: {
    name: Category2
  },
  categoryId3: {
    name: Category3
  }
}

products: {
  productId1: {
    name: Product 1,
    category: categoryId1, 
    price: 5
  },
  productId2: {
    name: Product 2,
    category: categoryId2, 
    price: 5
  },
  productId3: {
    name: Product 3,
    category: categoryId3, 
    price: 5
  }
}

I can retrieve both collections to the client and I can render lists with a v-for directive. I have a list of tabs rendered with all of the categories in my categories collection.

<div>
  <b-tabs content-class="mt-3">
    <b-tab v-for="category in categories" :title="category.name" :key="category.id"></b-tab>
  </b-tabs>
</div>

What I would like to accomplish next is to render a list of products in each tab with a condition. Where the product category value is equal to the tabs category.id

Something like this:

<div>
  <b-tabs content-class="mt-3">
    <b-tab v-for="category in categories" :title="category.name" :key="category.id">
    <li v-for="product in products" v-if="product.category === category.id" :key="product.id">
      {{ product.name }}
    </li>
  </b-tab>
  </b-tabs>
</div>

Can someone help to get that condition right please.


Solution

  • You need loop inside of the loop, like this:

    <div>
      <b-tabs content-class="mt-3">
        <b-tab v-for="category in categories" :title="category.name" :key="category.id">
        <template v-for="product in products" :key="product.name">
          <li v-if="product.category === category.id">
            {{ product.name }}
          </li>
        </template>
      </b-tab>
      </b-tabs>
    </div>