我创建了一个带有类别标签和每个类别复选框的表单,如下所示:
我正在使用axios以以下格式从Google表格获取值:
用于生成值的脚本:
data() {
return {
form: {
email: "",
name: "",
phoneNo: "",
checked: []
},
sports: [],
arts: [],
dance: [],
show: true
};
},
methods: {
getCcaList() {
this.axios
.get(
"(Google sheet batch get API)"
)
.then(response => {
let cellValues = response.data.valueRanges[0].values;
// cellValues[0][i] contains values of CCA cell
// cellValues[1][i] contains values of Category cell
for (let i = 0; i < cellValues[0].length; i++) {
if (cellValues[1][i] === "Sports")
this.sports.push(cellValues[0][i]);
else if (cellValues[1][i] === "Arts")
this.arts.push(cellValues[0][i]);
else if (cellValues[1][i] === "Dance")
this.dance.push(cellValues[0][i]);
}
});
}
具有vue-bootstrap的HTML设计:
<label for="sports">Sports:</label>
<br />
<b-form-checkbox-group v-model="form.checked" name="sports" :options="sports" stacked buttons></b-form-checkbox-group>
<br />
<label for="dance">Dance:</label>
<br />
<b-form-checkbox-group v-model="form.checked" name="dance" :options="dance" stacked buttons></b-form-checkbox-group>
<br />
<label for="arts">Arts:</label>
<br />
<b-form-checkbox-group v-model="form.checked" name="arts" :options="arts" stacked buttons></b-form-checkbox-group>
如果我决定在工作表中添加或删除类别,是否可以在不创建或删除数组的情况下创建上述格式?
到目前为止,我已经尝试过创建一个字典来存储Google表格中的值,并使用v-for显示类别值。但是,我无法按类别显示俱乐部数组中的每个值。
[
{ category: "Sports", club: ["Basketball", "Soccer", "Archery"] },
{ category: "Dance", club: ["Salsa"] },
{ category: "Arts", club: ["Painting", "Choir", "Band", "Drawing"] },
]
答案 0 :(得分:1)
您拥有字典的想法是正确的imo,您只需要更改模板即可。我用示例创建了一个沙箱:
https://codesandbox.io/s/dynamic-checkboxes-v1puy?fontsize=14&module=%2Fsrc%2FApp.vue
基本上你想做的就是拿字典
categories: [
{ category: "Sports", club: ["Basketball", "Soccer", "Archery"] },
{ category: "Dance", club: ["Salsa"] },
{ category: "Arts", club: ["Painting", "Choir", "Band", "Drawing"] }
],
然后使用v-for遍历它
<div v-for="c in categories" :key="c.category">
<label :for="c.category">{{c.category}}:</label>
<br>
<b-form-checkbox-group
:name="c.category"
v-model="form.checked"
:options="c.club"
stacked
buttons
></b-form-checkbox-group>
</div>
这样,无论何时添加新类别,模板都会处理它。