Component vue-multiselect- doesn't fetch value on load

1.1k views Asked by At

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

Screenshot

example

what am I doing wrong?

2

There are 2 answers

8
zerbene On BEST 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];
  }
0
demathos On

As mentionned in comments, you may pass the object itself to this.selectedBook. I suggest you to write your getFav function like this:

getFav() {
  let responseId = 2; // get the id from axios, for example 2
  let displayedItem = null;
  // map the books array to find the corresponding item id
  this.books.map(item => {
    if(item.id === responseId) {
      this.displayedItem = item;
    };
  });
  this.selectedBook = this.displayedItem;
}