Kevin
Kevin

Reputation: 335

Bootstrap VueJS Form select add Group Label

I have a concatenated two arrays and it shows on the ":options-"ObjOptions"". How to add "group labels" to respective existing arrays using this bootstrap VueJS?

Sample, dropdown options should look like this:

--Apple //group label
----apple1
----apple2
----apple3
----apple4

--Banana //group label
----banana1
----banana2
----banana3
----banana4
<b-form-group>
  <b-form-select id="backdrop-variant" v-model="selected :options="ObjOptions"></b-form-select>
</b-form-group>
export default {

  data() {
      return {
      selected: null,
      ObjOptions:'',
      Array1: ["apple1","apple2","apple3"],
      Array2: ["banana1","banana2","banana3","banana4"],
      };
  },
  created: function (){
      let arr1 = this.Array1;
      let arr2 = this.Array2;
      this.ObjOptions = arr1.concat(arr2);
  },
}

Upvotes: 0

Views: 379

Answers (1)

Hiws
Hiws

Reputation: 10364

Groups can be created by using an object in the options array.

This object needs to include a label property which will be displayed above the group, and a options property which will be each element in the group.

In the snippet below I've used a computed property instead of setting the array in the created hook, since it will be more reactive in case your Array1 or Array2 arrays change.

You can of course still use the created hook if you feel like it better fits your application.

new Vue({
  el: "#app",
  data() {
    return {
      selected: null,
      Array1: ["apple1", "apple2", "apple3"],
      Array2: ["banana1", "banana2", "banana3", "banana4"]
    };
  },
  computed: {
    ObjOptions() {
      const { Array1, Array2 } = this;

      return [
        {
          label: 'Apple',
          options: Array1
        },
        {
          label: 'Banana',
          options: Array2
        }
      ]
    }
  }
});
<link href="https://unpkg.com/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://unpkg.com/[email protected]/dist/bootstrap-vue.css" rel="stylesheet" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-vue.js"></script>

<div id="app">
  <b-select v-model="selected" :options="ObjOptions"></b-select>
</div>

Upvotes: 3

Related Questions