【问题标题】:Component vue-multiselect- doesn't fetch value on load组件 vue-multiselect- 在加载时不获取值
【发布时间】:2020-10-13 11:41:29
【问题描述】:

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

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

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

其实我得通过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>

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

如果你从列表中做出选择,那么模型就会改变

Screenshot

example

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    你只忘记了一行代码:在你的多选标签中添加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];
      }
    

    【讨论】:

    • v-model在代码中可用,加载组件时需要显示选中的,不需要选中多本书
    • 所以您希望通过加载组件预先选择默认书籍,并且在其下您也可以看到 id 和名称?
    • 这是我要实现的,编辑时常用的表格-下拉列表必须填写
    • 这有点不同 - 因为在 getFav() 响应中,指示符可能不是 1 而是其他一些 - 例如:29,然后如何在数组中搜索行号,其中ID = 29?
    • 所以如果我理解正确你的多选组件是父母的孩子。父母发送一个事件以使用书籍 ID 进行多选,这应该是默认书籍。并且多选将在加载时显示带有从父级接收到的 id 的书作为预选。
    【解决方案2】:

    正如 cmets 中提到的,您可以将对象本身传递给 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多