我正在使用VueJS 2和Vuetify构建下面的订阅表单。从服务器获取并显示适用于订阅的所有首选项的位置。图像中的首选项适用于数字杂志订阅。对于印刷杂志,订阅首选项可能会有所不同。
从服务器获取的数据看起来像这样
preferences: [
{
id: "1",
title: "Subscription frequence",
options: ["Daily", "Weekly", "Fortnight", "Monthly"]
},
{
id: "2",
title: "Topics",
options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"]
},
{
id: "3",
title: "Promotional Offers",
options: ["Daily", "Weekly", "Fortnight", "Monthly", "Never"]
}
]
我已经使用v-for
显示如下偏好设置:
<v-col
v-for="pref in preferences"
:key="pref.id"
>
<span>{{ pref.title }}</span>
<v-checkbox
v-for="option in pref.options"
:key="option"
:v-model="pref.options"
:label="option"
color="red"
value="option"
hide-details
>
</v-checkbox>
</v-col>`
现在,由于所有首选项都具有相同的options
数组,所以我不知道如何区分一个复选框组和另一个复选框组。因此,请为每个首选项组获得选中的复选框。
任何提示都非常感谢。谢谢。
在首选项对象中添加selectedOption键。
preferences: [
{
id: "1",
title: "Subscription frequence",
options: ["Daily", "Weekly", "Fortnight", "Monthly"],
selectedOption: []
},
{
id: "2",
title: "Topics",
options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"],
selectedOption: []
},
{
id: "3",
title: "Promotional Offers",
options: ["Daily", "Weekly", "Fortnight", "Monthly", "Never"],
selectedOption: []
}
]
<v-checkbox
v-for="option in pref.options"
:key="option"
:v-model="pref.selectedOption"
:label="option"
color="red"
value="option"
hide-details
>
首先,尝试向selected
数组内的每个对象添加一个空的preferences
数组:
preferences: [{
id: "1",
title: "Subscription frequence",
options: ["Daily", "Weekly", "Fortnight", "Monthly"],
selected: []
},
{
id: "2",
title: "Topics",
options: ["Sports", "Politics", "Art", "Music", "Health", "Tech"],
selected: []
},
{
id: "3",
title: "Promotional Offers",
options: ["Daily", "Weekly", "Fortnight", "Monthly", "Never"],
selected: []
}
]
下一步,在模板中,从以下位置更新v-checkbox
模型:
:v-model="pref.options"
to
:v-model="pref.selected"
现在,您可以轻松地在每个首选项中看到选定的选项,例如:
this.preferences[0].selected
this.preferences[1].selected
this.preferences[2].selected
简单演示:
new Vue({
el: '#app',
data: {
selected: [],
roles: [{id:1,name:"Client"},{id:2,name:"Admin"},{id:3,name:"Guest"}]
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<div v-for="role in roles" :key="role.id">
<label>{{role.name}}</label>
<input type="checkbox" v-model="selected" :value="role"/>
</div>
<p>Selected Roles:</p>
{{selected}}
</div>