When loading a component, I need to select the value in the drop-down list
I’m trying to make my code friends with vue-multiselect
found a similar topic – however, nothing appears in the field – if you then select a value, everything works correctly link
in fact, I have to download via axios, the mini version looks like this
import Multiselect from "vue-multiselect"; export default { components: { Multiselect }, data() { return { books: [], selectedBook: null, }; }, created() { this.getBooks(); this.getFav(); }, methods: { //through axios I get the model and pass it to the list component getBooks() { this.books = [ { id: 1, name: "ABC" }, { id: 2, name: "QWE" } ]; }, getFav() { //through axios I get the Id of the model for editing let responseId = 1; this.selectedBook = responseId; }, <template> ... <multiselect v-model="selectedBook" :options="books" :selected="selectedBook" track-by="id" label="name" :show-labels="false" placeholder="Choose your book"> <span slot="noResult">No books were found</span> </multiselect> <pre class="language-json"><code>{{ selectedBook }}</code></pre> ... </template>
but when the form is loaded and opened – there is nothing in the select box,
and if you make a choice from the list, then the model changes
what am I doing wrong?
Advertisement
Answer
You forget just one line of code: in your multiselect tag add v-model="selectedBook"
, like
<multiselect :options="books" :selected="selectedBook" :show-labels="false" track-by="id" label="name" placeholder="Choose your book" v-model="selectedBook" >
And if you want a book to be already selected when you load the component (so a default book, for example the first one). You have to modify your getFav() function, which is called when creating the component:
getFav() { var fav = 1; /*id of the book to display*/ var defaultIndex = this.books.findIndex(x => x.id === fav); this.selectedBook = this.books[defaultIndex]; }