vue multiselect 1.1.4,按id选择值

时间:2017-01-10 06:25:30

标签: vue.js vue-component

我添加了看起来像这样的多选组件

查看

<multiselect
  :options="books"
  :selected="selectedBook"
  :show-labels="false"
  placeholder="Choose your book"
  label="name">
  <span slot="noResult">No books were found</span>
</multiselect>

脚本

<script>
  export default {
    data() {
      return {
        books: [],
        selectedBook: null,
      }
    },
    created() {
      this.getBooks();
      this.getFav();
    },
    methods: {
      getBooks() {
        this.$http
        .get('/books/')
        .then(
          function(response) {
            this.books = response.json();
          }
        );
      },
      getFav() {
        this.$http
        .get('/fav/')
        .then(
          function(response) {
            var fav = response.json();
            this.selectedBook = fav.id;
          }
        );
      }
    }
  }
</script>

响应

[{"id":1,"name":"ABC"},{"id":2,"name":"QWE"}]

我的问题是,如何通过id设置所选书籍。当我这样设置,然后在输入显示id,但我想要书名。

1 个答案:

答案 0 :(得分:3)

使用track-by

<multiselect
  ...
  track-by="id"
  label="name"
  ...
>

参考:https://vue-multiselect.js.org/#sub-single-select-object