如何在Vue.js中设置optgroup选择标签?

如何在Vue.js中设置optgroup选择标签?

问题描述:

我正在尝试在Vue中进行选择.

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

提琴: https://jsfiddle.net/Tropicalista/vwjxc5dq/

我已经尝试过了:

<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>

我的数据:

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

您正在将label属性绑定到作为数组的option.您要绑定到对象的键.

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

您可以通过在v-for指令中指定第二个参数来获取每个选项的键:

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">


我还将您的options属性重命名为optionGroups以避免进一步的混乱:


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>