如何在 Vue.js 中设置 optgroup 选择标签? [英] How to set optgroup select label in Vue.js?

查看:21
本文介绍了如何在 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>

这篇关于如何在 Vue.js 中设置 optgroup 选择标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆