[Vuejs]-Nested v-for loop in vue

0👍

Looks like you have an error in you’re orders list. You can change the list to contain a list of product which is then accessible through the v-for mapping.

Order list:

orders: [
  {
    _id: "0132asd943",
    products: [
      {
        _id: "3i412e39",
        title: "Porduct 1",
        price: "239"
      },
      {
        _id: "kad83423",
        title: "Porduct 2",
        price: "699"
      }
    ],
    user: {
      name: "user1",
      email: "user1@mail.com"
    }
  }
]

Mapping:

<div v-for="item in orders" v-bind:key="item.id">
  <li>{{item.products[0]}}</li>
  <li>{{item.products[1]}}</li>
</div>

Working example:
codesandbox

0👍

As the Vue warning indicated, <template>s cannot be keyed. The key needs to be on the <template>‘s root children (i.e., <tr> in this case). Since the root child (<tr>) is already keyed, you don’t need to apply another key.

The solution here is simply to remove the key from <template>. Also, note that the inner v-for iterates orders[].products[], each of which contains an id field, which would be a better key than the index because of the id‘s uniqueness.

<tbody>
  <!-- BEFORE: -->
  <!-- <template v-for="(item, index) of orders" :key="index"> -->
  <template v-for="(item, index) of orders">

    <!-- BEFORE: -->
    <!-- <tr v-for="(prod, j) of item.products" :key="j"> -->
    <tr v-for="(prod, j) of item.products" :key="prod.id">
    
    ...

    </tr>
  </template>
</tbody>

demo

Leave a comment