user892134
user892134

Reputation: 3214

vuejs loop through items, every 3 items new row

Currently i have this code, which shows 3 items in each row.

<b-container class="tags">
<b-row v-for="index in 3" :key="index">
   <b-col>
      <MovieItem />
   </b-col>
   <b-col>
      <MovieItem />
   </b-col>
   <b-col>
      <MovieItem />
   </b-col>
</b-row>
</b-container>

Now i have returned results from api and i want in the same format as above. I know how to loop through results but how do i add wrap the code in b-col and b-row so it is same format as above?

<b-container class="tags">
    <MovieItem  v-for="(movie,index) in MovieItems" :key="index" />
</b-container>

How do i solve?

Upvotes: 0

Views: 1174

Answers (1)

akuiper
akuiper

Reputation: 215117

Based on the length of MovieItems, you can calculate how many rows are needed with Math.floor((MovieItems.length - 1) / 3) + 1:

computed: {
  nrows() {
    return Math.floor((MovieItems.length - 1) / 3) + 1;
  }
}

In your template, use a nested loop assuming MovieItem component takes movie as a prop:

<b-row v-for="row in nrows" :key="row">
   <b-col v-for="col in 3" :key="col">
      <MovieItem :movie="MovieItems[row * 3 + col] v-if="row * 3 + col < MovieItems.length" />
   </b-col>
</b-row>

Upvotes: 2

Related Questions