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' }
]
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With