Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set optgroup select label in Vue.js?

I'm trying to make a select group in Vue.

Fiddle: https://jsfiddle.net/Tropicalista/vwjxc5dq/

I've tried this:

<optgroup v-for="option in options" v-bind:label="option">
  <option v-for="sub in option" v-bind:value="option.value">
   {{ sub.text }}
  </option>
</optgroup>

My data:

data: {
  selected: 'A',
  options: {
    First: [
      { text: 'One', value: 'A' },
      { text: 'Two', value: 'B' }
    ],
    Second: [
     { text: 'Three', value: 'C' }
    ]
  }
}
like image 772
Tropicalista Avatar asked May 05 '17 19:05

Tropicalista


1 Answers

You are binding the label attribute to option, which is an array. What you want is to bind to the object's key.

You can get the key of each option by specifying a second parameter in the v-for directive:

<optgroup v-for="(option, key) in options" v-bind:label="key">

I'd also rename your options property to optionGroups to avoid further confusion:

data: {
  selected: 'A',
  optionGroups: {
    First: [
      { text: 'One', value: 'A' },
      { text: 'Two', value: 'B' }
    ],
    Second: [
      { text: 'Three', value: 'C' }
    ]
  }
}

That way, the template will make more sense:

<optgroup v-for="(group, name) in optionGroups" :label="name">
  <option v-for="option in group" :value="option.value">
    {{ option.text }}
  </option>
</optgroup>
like image 185
thanksd Avatar answered Sep 23 '22 19:09

thanksd