Passing array of objects from vue to laravel using vue-multiselect

Viewed 551

I am using the vue multiselect package and when using the <multiselect> in place of the traditional <select> I am running into an issue. In my vue component I am passing in a prop which contains an array of object and each of those objects has various properties. With a traditional select in vue you can loop through the array using v-for and then pass the value based on object.id, is there a way to do this with the vue-multiselect package? Not sure if anyone has tried to use this as part of a form before but Its worth asking. Thanks.

My Vue File

<multiselect
        v-model="users"
        :options="usersArray"
        :multiple="true"
        :clear-on-select="false"
        :preserve-search="false"
        placeholder="select users"
        label="name"
        track-by="name"
        :preselect-first="false"
        id="users"
        name="users[]"
    ></multiselect>


export default {
  props: {
    'usersArray': Array,
  },
  data(){
    return {
      users: [],
    }
  },
1 Answers

You need to customize the label and options for multi-select. For this.

:options="usersArray.map(user => user.id)" 
:custom-label="opt => usersArray.find(x => x.id == opt).name"

The working snippet below :

new Vue({
  components: {
    Multiselect: window.VueMultiselect.default
  },
  data: {
    users: [],
    usersArray: [{
        id: 1,
        name: "A"
      },
      {
        id: 2,
        name: "B"
      },
      {
        id: 3,
        name: "C"
      },
      {
        id: 4,
        name: "D"
      },
    ]
  },
}).$mount('#app')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://unpkg.com/vue-multiselect@2.1.6"></script>
<link rel="stylesheet" href="https://unpkg.com/vue-multiselect@2.1.0/dist/vue-multiselect.min.css">
<div id="app">
  <multiselect v-model="users" :options="usersArray.map(user => user.id)" :custom-label="opt => usersArray.find(x => x.id == opt).name" :multiple="true" :clear-on-select="false" :preserve-search="false">
  </multiselect>
  <pre>{{ users }}</pre>
</div>

Related