Axios呼叫,使用vue将响应数据纳入选择选项

时间:2019-04-11 14:40:53

标签: javascript laravel vue.js axios

我在这里要做的只是弄清楚如何将响应数据值绑定到多选$args1 = array( 'taxonomy'=> 'portfolio_cat', 'orderby' => 'slug', 'order' => 'ASC', ); $cats = get_categories($args1); foreach ($cats as $cat) { //echo $cat->slug; $args2 = array( 'post_type' => 'advanced_portfolio', 'posts_per_page' => -1, //'tag_id' => 25, // 'category_name' =>$cat->slug, 'category_name' =>'video' //my category name **slug** ); query_posts($args2); if (have_posts()) : while (have_posts()) : the_post(); the_title(); endwhile; endif; } 中,但是我无法弄清楚自己在做什么错。

控制台日志正确显示了我返回的结果,因此我知道它们已返回,但我不知道如何将它们绑定到我的多选选项中。

例如,如果我在多选中键入“ Day”,则axios调用将执行自动完成功能并获取匹配选项,以便控制台显示:

options

那么如何将这些返回的值放入我的选项中?

 0:
    tag_id:  "1001"
    tag_data: "First Day"
 1:
    tag_id:   "1002"
    tag_data: "Second Day"

2 个答案:

答案 0 :(得分:1)

由于您使用对象作为选项,因此需要将labeltrack-by属性传递给multiselect组件。参见文档here

<multiselect
  v-model="value"
  label="tag_data"
  track-by="tag_id"
  :options="options"
  :loading="loading"
  :multiple="true"
  :taggable="true"
  @search-change="val => read(val)"
></multiselect>

答案 1 :(得分:1)

您需要添加label属性和track-by属性。在我的示例中,title是我用作options的对象的属性,因此您需要使用存在于用作options的数组中的属性名称..

CodePen镜像:https://codepen.io/oze4/pen/ROVqZK?editors=1010

Vue.component("multiselect", window.VueMultiselect.default);

new Vue({
  el: "#app",
  data: {
    value: [],
    options: []
  },
  mounted() {
    var self = this;
    axios
      .get("https://jsonplaceholder.typicode.com/todos?_start=1&_end=10")
      .then(response => {
        self.options = response.data;
      })
      .catch(error => {
        alert(error);
      });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<script src="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">

<div id="app">
  <label class="typo__label">Simple select / dropdown</label>
  <multiselect 
    v-model="value" 
    :height="300"
    :options="options" 
    :multiple="true" 
    :close-on-select="false" 
    :clear-on-select="false" 
    :preserve-search="true" 
    placeholder="Pick some" 
    label="title" 
    track-by="title" 
    :preselect-first="false"
  >
    <template slot="selection" slot-scope="{ values, search, isOpen }"><span class="multiselect__single" v-if="values.length &amp;&amp; !isOpen">{{ values.length }} options selected</span></template>
  </multiselect>
  <pre class="language-json"><code>{{ value }}</code></pre>
</div>