Search code examples
javascriptvue.jsvue-multiselect

Properly tracking options in vue-multiselect


I'm currently using an axios call to preform an auto-complete with Vue-multiselect. I'm now getting my data back from the query and can see it when dumping it in the console, but I'm still not connecting somewhere as far as loading my array with options and tracking them in the multiselect component.

Right now, my response.data looks like this:

0:
  contact: [email protected]
1:
  contact: [email protected]

I simply want the contact field to be what shows up as their select options and I also want that to be what I send in a later submission so I want to label AND track by that one field.

What am I doing wrong here?

<multiselect 
   v-model="copyUsers" 
   :options="copyUsersOptions" 
   @search-change="val => searchCopiedUsers(val)"
   :multiple="true" 
   :loading="loading"
   placeholder="Enter user(s) to be copied" 
   label="name"
   track-by="value">
 </multiselect>

 data() {
    return {
        loading: false,
         copyUsers: [],
         copyUsersOptions: [],
    }
 },
 methods: {
    searchCopiedUsers: function(val) {
          console.log('searched for', val);
          if (val) {
            this.loading = true;

            axios.get('/users/search',{params: {query: val}})
            .then(response => {
                
                this.copyUsersOptions = response.data;

                console.info(this.copyUsersOptions);

                
              })
              .catch(function(error) {
                this.loading = false;
                console.log(error)
              })
              .finally(function() {
                this.loading = false;
              })

          } else {
            this.copyUsersOptions = [];
          }
    },
}

Solution

  • Try casting your object to an array

    axios.get('/users/search',{params: {query: val}})
        .then(response => {
            this.copyUsersOptions = [...response.data];
        })
    

    Currently, your result from your server is an object. Which from your initialization of vue-multiselect will not work. By converting it to an array using the spread operator, the array will be formatted correctly.