Bootstrap vue select 从对象列表中获取对象 b-form-select
Bootstrap vue selecting the object from a list of objects b-form-select
尽管我找到了问题的解决方案,但我对它的解决方式还是有些不满意。有没有办法让这更简单?在理想情况下,我会有类似的 html,我唯一要做的就是调用 api 来获取教师并立即将他们分配给 this.teachers
,而不必遍历他们创建一些新对象的无类型数组。
HTML:
<b-form-select
v-model="selectedTeacher"
:options="teachers"
value-field="teacher" //NOT teacher.id, I want the object itself
text-field="teacher.name">
</b-form-select>
JS
var dbTeachers: Teacher[] = await getTeachers();
dbTeachers.forEach(teacher => {
this.teachers.push(new Object({
teacher: teacher ,
name: teacher.name
}));
});
您可以将整个对象绑定到 <option>
标签的 value
。因此,您可以使用 v-for
指令手动创建 <option>
,而不是使用 options
道具。
这样您将在 <b-form-select>
的 v 模型中获得整个对象。
new Vue({
el: "#app",
data() {
return {
selectedItem: null,
options: [
{ id: 1, name: 'Mike Macdonald', age: 42 },
{ id: 2, name: 'Larsen Shaw', age: 27 },
{ id: 3, name: 'Jami Cord', age: 81 },
],
}
}
})
<link href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.js"></script>
<div id="app" class="p-3">
<b-form-select v-model="selectedItem">
<option :value="null" disabled>-- Please select an option --</option>
<option v-for="option in options" :value="option">
{{ option.name }}
</option>
</b-form-select>
Selected option: {{ selectedItem }}
</div>
尽管我找到了问题的解决方案,但我对它的解决方式还是有些不满意。有没有办法让这更简单?在理想情况下,我会有类似的 html,我唯一要做的就是调用 api 来获取教师并立即将他们分配给 this.teachers
,而不必遍历他们创建一些新对象的无类型数组。
HTML:
<b-form-select
v-model="selectedTeacher"
:options="teachers"
value-field="teacher" //NOT teacher.id, I want the object itself
text-field="teacher.name">
</b-form-select>
JS
var dbTeachers: Teacher[] = await getTeachers();
dbTeachers.forEach(teacher => {
this.teachers.push(new Object({
teacher: teacher ,
name: teacher.name
}));
});
您可以将整个对象绑定到 <option>
标签的 value
。因此,您可以使用 v-for
指令手动创建 <option>
,而不是使用 options
道具。
这样您将在 <b-form-select>
的 v 模型中获得整个对象。
new Vue({
el: "#app",
data() {
return {
selectedItem: null,
options: [
{ id: 1, name: 'Mike Macdonald', age: 42 },
{ id: 2, name: 'Larsen Shaw', age: 27 },
{ id: 3, name: 'Jami Cord', age: 81 },
],
}
}
})
<link href="https://unpkg.com/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vue@2.6.12/dist/vue.min.js"></script>
<script src="https://unpkg.com/bootstrap-vue@2.21.2/dist/bootstrap-vue.js"></script>
<div id="app" class="p-3">
<b-form-select v-model="selectedItem">
<option :value="null" disabled>-- Please select an option --</option>
<option v-for="option in options" :value="option">
{{ option.name }}
</option>
</b-form-select>
Selected option: {{ selectedItem }}
</div>