javascriptvue.jsaxiosvue-multiselect

How can I sent v-modal as array for Axios params?


I have a Vue Multiselect instance that's working properly, but my v-model is an array (since multiple options can be selected). The issue is that I want to call a route within the loadExtraOptions method that will except the array of IDs as a param (The ids would be the catNum value for each index in the array). I have params set in the axios call but it is currently just the model as a whole, how can I properly send the array of IDs in for that param?

<multiselect
v-model="categoryModel"
:options="categoryOptions"
:multiple="true"
placeholder="Select Categories"
:close-on-select="true"
label="catNum"
track-by="catNum"
@select="loadExtraOptions"
></multiselect>

var vm = 
new Vue({
  el: "#app",
  props: { 

  },
  components: {Multiselect: window.VueMultiselect.default},
  data: {
        categoryModel: [],
        categoryOptions: [],
  },
  methods: {
    loadExtraOptions(){
      console.log(this.categoryModel);
      if(categoryModel.length > 0){
         axios.get('/test/route/autocomplete/category',{
            params: {
              categories:this.categoryModel
            }
         })
         .then((res) => {
              
            })
            .catch((error) => {
              
            });
      }
    },
 }
});

Solution

  • With .map you can only extract the id from the model.

    this.categoryModel.map(category => category.id)
    

    The GET request send parameters as a query string. So you need to send the ids as a string, not as array, as in the format below.

    // For example,
    // categoryModel: [{id: 1}, {id: 2}, {id: 3}]
    // result: 1,2,3
    this.categoryModel.map(category => category.id).join(',')