javascripttwitter-bootstraptemplatesvue.jsbootstrap-4

How to add <div class="row"> every 2 elements while looping in Vue.JS template?


I got an array of images's URL of variable length in my model.

I'd like to show on my page 2 images per row, and get a result like this:

<div class="row">
  <div class="col">
    <img ... />
  </div>
  <div class="col">
    <img ... />
  </div>
</div>
<div class="row">
  <div class="col">
    <img ... />
  </div>
  <div class="col">
    <img ... />
  </div>
</div>
...

But I just don't figure out how to conditionally add the opening and closing tags of row.

This is what I tried but it doesn't work:

I'm using boostrap-vue, so b-container, b-row and b-col are basically <div class="container">, and <div class="col">.

<b-container>
  <template v-for="(url, index) in urls">
    <template v-if="index % 2 == 0">
      <b-row :key="index">
    </template>
    <b-col :key="index">
      <p>{{ index }}</p>
      <b-img
        :src="url"
        alt="charts"
        fluid
      ></b-img>
    </b-col>
    <template v-if="index % 2 == 0">
      </b-row>
    </template>
  </template>
</b-container>

And the error:

 Errors compiling template:

  tag <b-row> has no matching end tag.

  40 |      <template v-for="(url, index) in urls">
  41 |        <template v-if="index % 2 == 0">
  42 |          <b-row :key="index">
     |          ^^^^^^^^^^^^^^^^^^^^
  43 |        </template>
  44 |        <b-col :key="index">

Solution

  • I would restructure your image array using a computed property that returns an array chunked into groups of two images. You could even conditionally change the chunk size to increase or decrease the number of images in a row.

    computed: {
       makeRows(){
         let row = [];
         let i,l, chunkSize = this.rowSize; 
    
         for (i=0,l=this.images.length; i<l; i+=chunkSize) {
           row.push(this.images.slice(i,i+chunkSize));
    
         }
         return row;
         }
      }
    

    Here is a working example using an array. https://jsfiddle.net/skribe/0fvj5643/7/