Search code examples
vue.jsvuejs2vue-componentv-select

How to use v-select but not repeat itself while using v-for


I have array of json in groupData, how to pass the data to v-select

I know what I am doing is wrong by using v-for inside v-select, but I am not sure how to pass data:

<v-select multiple
  v-for="group in groupsData"
  :value.sync="selected"
  :options="[{label: group.group_name, value: group.id}]">
</v-select>

Plugin URL: https://sagalbot.github.io/vue-select/

This is how it's done with vue.js without v-select plugin and this works:

<select v-model="selected" multiple>
  <option v-for="group in groupsData" v-bind:value="group.group_id">{{group.group_name}}</option>
</select>

Thanks in advance.


Solution

  • Typically I use a computed property.

    new Vue({
      el:"#app",
      data:{
        groupsData: groups,
        selected:[]
      },
      computed:{
        selectOptions(){
          return this.groupsData.map(g => ({label: g.group_name, value: g.id}))
        }
      }
    })
    

    And in your template

    <v-select multiple
              :value.sync="selected"
              :options="selectOptions">
    </v-select>
    

    Working example.