我正在尝试在 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
,这是一个数组。您想要的是绑定到对象的键。
您可以通过在
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>
根据上面的回答。我通过在 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>
这是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>