0

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

我正在尝试用 vue-multiselect 让我的代码成为朋友

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

其实我得通过axios下载,mini版是这样的

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>

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

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

截屏

例子

我究竟做错了什么?

4

2 回答 2

2

您只忘记了一行代码:在您的多选标签中添加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];
  }
于 2020-10-13T12:11:43.107 回答
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;
}
于 2020-10-13T13:05:32.217 回答