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

编程入门 行业动态 更新时间:2024-10-24 16:28:27
本文介绍了如何在 Vue.js 中设置 optgroup 选择标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Vue 中创建一个选择组.

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

小提琴:https://jsfiddle/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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-31 09:58:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/801926.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:标签   如何在   js   Vue   optgroup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!