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

问题描述 投票:0回答:3

我正在尝试在 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' }
    ]
  }
}
javascript jquery vue.js vuejs2
3个回答
19
投票

您将

label
属性绑定到
option
,这是一个数组。您想要的是绑定到对象的键。

您可以通过在

v-for
指令中指定第二个参数来获取每个选项的键:

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

我还将您的

options
属性重命名为
optionGroups
以避免进一步混淆:

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

这样,模板就会更有意义:

<optgroup v-for="(group, name) in optionGroups" :label="name">
  <option v-for="option in group" :value="option.value">
    {{ option.text }}
  </option>
</optgroup>

0
投票

根据上面的回答。我通过在 optgroup 标签中添加标签来改进 optgroup 标签

<optgroup v-for="(group, name) in optionGroups" :key="name" :label="`${name}`">
                
 <option v-for="option in group" :key="option.value">
   {{ option.text }}
    </option>
 </optgroup>

0
投票

这是Vue3组合API版本:

<script setup>
import { ref } from 'vue'

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

const selected = ref('A');
</script>

<template>
  <select v-model="selected">
    <optgroup v-for="(group, groupName) in options" :label="groupName" :key="groupName">
      <option v-for="item in group" :value="item.value" :key="item.value">
        {{ item.text }}
      </option>
    </optgroup>
  </select>

  <p>Selected value: <span>{{ selected }}</span></p>
</template>
© www.soinside.com 2019 - 2024. All rights reserved.