组件vue-multiselect-无法在加载时获取值

时间:2020-10-13 11:41:29

标签: javascript vue.js vuejs2 nuxt.js vue-multiselect

加载组件时,我需要在下拉列表中选择值

我正在尝试通过vue-multiselect结识我的代码

找到了类似的主题-但是,该字段中没有任何内容-如果您随后选择一个值,则一切正常link

实际上,我必须通过axios下载,迷你版看起来像这样

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>

但是在加载和打开表单时-选择框中没有任何内容,

如果您从列表中进行选择,则模型会更改

Screenshot

example

我在做什么错了?

2 个答案:

答案 0 :(得分:2)

您只会忘记一行代码:在您的multiselect标记中添加v-model="selectedBook",就像

<multiselect
 :options="books"
 :selected="selectedBook"
 :show-labels="false"
 track-by="id"
 label="name"
 placeholder="Choose your book"
 v-model="selectedBook" 
>

如果您希望在加载组件时已经选择一本书(因此是默认书,例如第一本书)。您必须修改getFav()函数,该函数在创建组件时会被调用:

  getFav() {
    var fav = 1; /*id of the book to display*/
    var defaultIndex = this.books.findIndex(x => x.id === fav);
    this.selectedBook = this.books[defaultIndex];
  }

答案 1 :(得分:0)

如注释中所述,您可以将对象本身传递给this.selectedBook。我建议您这样编写getFav函数:

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;
}