如何将Axios与Vue-Multiselect结合使用?

时间:2019-02-11 21:20:40

标签: vuejs2 vue-multiselect

使用Vue-Multiselect的新功能。我正在使用axios从JSON占位符发出GET请求进行测试。

如何获取标题和帖子ID,以显示在下拉菜单中?

现在,我刚在选择框中显示[对象对象]-[标题]。

enter image description here

    <!-- Vue component -->
<template>
  <div>
    <multiselect v-model='value' :options='posts' :custom-label='postWithTitle' placeholder='Select one' label='title' track-by='id'></multiselect>
    {{ value  }}
  </div>
</template>

<script>
import Multiselect from "vue-multiselect";
import axios from "axios";

export default {
  // OR register locally
  components: { Multiselect },
  data() {
    return {
      value: null,
      posts: []
    };
  },
  created() {
    this.getPosts();
  },
  methods: {
    getPosts() {
      axios
        .get("https://jsonplaceholder.typicode.com/posts")
        .then(response => {
          // eslint-disable-next-line
          console.log(response);
          this.posts = response.data;
        })
        .catch(error => {
          // eslint-disable-next-line
          console.log(error);
        });
    },
    postWithTitle(id, title) {
      return `${id} - [${title}]`;
    }
  }
};
</script>

1 个答案:

答案 0 :(得分:0)

修复:

  postWithTitle(option) {
     return `${option.id} - [${option.title}]`;
  }

说明:

当我简单地console.log进入postWithTitle函数内部时,我发现:

自定义custom-label属性正在接受仅接受一个参数的回调。该参数是整个option对象-posts数组的单个条目。