Even though I got the solution to my problem I'm slightly unsatisfied with how it's solved. Is there a way to make this simpler? As in, ideally I would have similar html and the only thing I would do is make a call to api to get the teachers and immediately assign them to this.teachers
instead of having to iterate through them to make an untyped array of some new object.
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
}));
});
You can bind the entire object to the value
of an <option>
tag. So instead of using the options
prop you would manually create the <option>
using the v-for
directive.
That way you'll get the entire object in the <b-form-select>
's v-model.
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>