1 回答
TA贡献2041条经验 获得超4个赞
我建议您将数据构建在嵌套的对象数组中(此处计算:nestedOptions -method),以便您的数据如下所示:
nestedOptions: [
{
name: "sport",
options: [
{ id: 1, text: "Football", group: "sport" },
{ id: 2, text: "Basketball", group: "sport" },
]
},
{
name:"food"
options: [...]
}
]
跟踪选定的选项以及选定的组。
为选定的组做一个观察者......如果它们发生变化,则相应地更改选定的选项:
export default {
name: "groupedOptionsComponent",
data() {
return {
selectedOptions: [],
selectedGroups: [],
optionsList: [
{ id: 1, text: "Football", group: "sport" },
{ id: 2, text: "Basketball", group: "sport" },
{ id: 3, text: "Cookie", group: "food" },
{ id: 4, text: "Soup", group: "food" }
],
optionsGroupsList: ["sport", "food"]
};
},
computed: {
nestedOptions() {
return this.optionsGroupsList.map(groupName => ({
name: groupName,
options: this.optionsList.filter(({ group }) => group === groupName)
}));
}
},
watch: {
selectedGroups: function(groups) {
this.optionsList.forEach(option => {
if (
groups.includes(option.group) &&
!this.selectedOptions.includes(option.id)
) {
this.selectedOptions.push(option.id);
} else {
this.selectedOptions = this.optionsList
.filter(({ group }) => groups.includes(group))
.map(({ id }) => id);
}
});
}
}
};
使您的模板看起来像这样:
<template>
<div>
<div v-for="(group, index) in nestedOptions" class="checkbox-group" :key="index">
<vs-checkbox :vs-value="group.name" v-model="selectedGroups">{{ group.name }}</vs-checkbox>
<vs-checkbox
v-for="option in group.options"
:vs-value="option.id"
:key="option.id"
v-model="selectedOptions"
>{{ option.text }}</vs-checkbox>
</div>
</div>
</template>
添加回答
举报