首页 > 解决方案 > 使用 Vue Multiselect 在选择/输入时调用 Axios

问题描述

我有一个功能正常的 Vue Multiselect,我正在使用 axios 调用从我的数据库值中填充选项。这非常有效,允许我从现有选项中进行选择或输入新选项以创建标签。

事实上,这非常有效。但是如果可能的话,我需要一种方法来在每次用户选择和选项或按回车键保存标签选项时进行另一个 Axios 调用。有没有办法做到这一点?

这是我对 Vue 的第一次体验,我真的不确定这是否可行,但基本上我只是想知道每次选择或使用 enter 键输入标签时如何进行 axios 调用

<div id="tagApp">
  <multiselect
  label="tag_data"
  track-by="campaign_tag_id"
  v-model="value"
  :options="options"
  :multiple="true"
  :taggable="true"
  @tag="addTag"
  @search-change="val => read(val)"
  :preselect-first="false"
  :close-on-select="false" 
  :clear-on-select="true" 
  :preserve-search="true" 
  tag-placeholder="Add this as new tag" 
  placeholder="Search or add a tag"
  ></multiselect>
</div>

new Vue({
      components: {
        Multiselect: window.VueMultiselect.default
      },
      el: "#tagApp",
      data() {
        return{
            value: [],
            loading: false,
            options: []
        }

      },
      methods: {
        read: function(val){
            //console.log('searched for', val);
          if (val) {
            this.loading = true;
            this.options = [];

            const self = this;
            console.log(val);

            axios.get('campaigns/search',{params: {query: val}})
                .then(function (response) {
                    self.options = response.data;
                    console.log(response.data);
            });

          } else {
            this.options = [];
          }
        },
        addTag(newTag) {
          const tag = {
            tag_data: newTag,
          };
          this.options.push(tag);
          this.value.push(tag);
        }
      }
    })

标签: javascriptvue.jsaxiosmulti-select

解决方案


监控@select 事件并触发您的 Axios 调用将发生的函数。

<div id="tagApp">
  <multiselect
  ...
  @select= "callAxios"
  ...
  ></multiselect>
</div>
...

   methods: {
        callAxios: function(val){
            //your Axios call here
        },
        ...
   }

...


推荐阅读