Skip to content
Advertisement

VueJS – Conditionally wrap inside a div

I have a v-for loop on VueJS and I want to wrap the loop elements inside a div in groups of two.

For example:

<div class="xpto" v-for="item in items"> //this div should wrap a maximum of two components per time
  <component :item="item"></component>
</div>

What would be the best way to achieve that?

Advertisement

Answer

You can achieve this by referencing the index of each item and getting the item from the items array at the calculated index:

<div 
  class="xpto" 
  v-for="n, i in items.length" 
  v-if="i < items.length / 2"
>
  <component 
    v-for="m, j in 2" 
    v-if="items[i*2+j]" 
    :item="items[i*2+j]"
  ></component>
</div>
Advertisement