Home > database >  What is the proper way to use v-select ,item-text and item-value?
What is the proper way to use v-select ,item-text and item-value?

Time:05-19

This is the response of api i call

enter image description here from another view.

enter image description here

I am storing the api result lets say in result = [];. I am creating a drop down list using v-select with :items="result" . How should i write for item-text and item-value if i want services.name to be the text shown on dropdown list and services._id will be stored in an var using v-model , services._id as a item-value. I can't seem to figure out these nested properties.

CodePudding user response:

Something you can do is retrieve all the services from all the sub arrays through a computed property.

Then you will only have one array of object (instead of an array of arrays through the property services) and you can specify the item-text and item-value properties !

Here is an example

new Vue({
  el: "#app",
  vuetify: new Vuetify(),
  data: () => {
    return {
      currentItem: null,
      items: [{
          services: [
            {_id: 1,name: 'foo'},
            {_id: 2, name: 'bar'}
          ]
        },
        {
          services: [
            {_id: 1,name: 'foo'}, 
            {_id: 3, name: 'baz'} 
          ]
        }
      ]
    }
  },
  
  computed: {
    allServices(){
      return this.items.reduce((acc, curr) => {
        curr.services.forEach(service => {
          if(!acc.find(x => x._id === service._id)) acc.push(service)
        })
        return acc
      }, [])
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vuetify.min.css" />

<div id="app" data-app>
  currentItem : {{currentItem}}
  <v-select v-model="currentItem" :items="allServices" item-text="name" item-value="_id"></v-select>
</div>

CodePudding user response:

You can use the slots of the v-select to customize the shown data:

<v-select
    label="Services"
    v-model="customVar"
    :items="result"
    item-value="_id"
    item-text="name"
    return-object
  >
    <template v-slot:selection="data">
      {{ data.item.name }}
    </template>
    <template v-slot:item="data">
      {{ data.item.name }}
    </template>
  </v-select>

Also you could use as shown above return-object:

Changes the selection behavior to return the object directly rather than the value specified with item-value

So you could choose wich variables you use from the selected object

  • Related