Search code examples
javascriptarraysobjectvue.jsv-for

How do I loop through an array in Vue half the amount of times as there are items?


I have an array of data:

[
  {
    type: select, 
    options: [foo, bar], 
    label: foo, 
    required: true
  }, 
  {
    type: text, 
    options: [],
    label: bar, 
    required: false
  }, 
  {
    type: checkbox, 
    options: [], 
    label: baz, 
    required: true
  }
]

and a Vue template:

<b-row>
  <b-col>
    <label :for="{{label}}">{{ label }}<span class="required" v-if="required"/></label>
    {{ checks type and injects proper form element here }}
  </b-col>
</b-row>

I'm trying to figure out how best to loop through each object, and place each one into its own <b-col>, with only two columns per row so that it looks similar to the following structure:

<b-row>
  <b-col>
    <label for="size">foo<span class="required" v-if="required"/></label>
    <b-form-select id="size">
      <options>foo</options>
      <options>bar</options>
    </b-form-select>
  </b-col>
  <b-col>
    <label for="size">bar<span class="required" v-if="required"/></label>
    <b-form-text id="size"/>
  </b-col>
</b-row>
<b-row>
  <b-col>
    <label for="size">baz<span class="required" v-if="required"/></label>
    <b-form-select id="size"/>
  </b-col>
    <label for="size">barbaz<span class="required" v-if="required"/></label>
    <b-form-select id="size"/>
  </b-col>
</b-row>
...etc.

I'm struggling to find the best approach to accomplish this cleanly and in a vue-like manner.


Solution

  • You can just iterate through the array, place each element inside a b-col and specify the width of each of those columns to be 50%, like this:

    <b-row>
        <b-col v-for="item in array" sm="6">
            ...do something with item
        </b-col>
    </b-row>
    

    sm="6" tells bootstrap to use the amount of space equal to 6 columns (i.e. 50%) I am not sure about vue-bootstrap, but the bootstrap documentation states:

    If more than 12 columns are placed within a single row, each group of extra columns will, as one unit, wrap onto a new line

    https://getbootstrap.com/docs/4.1/layout/grid/#column-wrapping