Search code examples
vue.jsvuetify.jsv-selectv-autocomplete

Add custom data attribute to Vuetify v-select options


I am using a v-autocomplete component to list items in a selector. Since v-autocomplete is just an advanced v-select, I think an answer for v-select would work for v-autocomplete too.

In my list I have items with different statuses which should be marked in some way. So I want to add a data attribute to the options depending on an item property. If I can add at least a different class, that would help too. But since I don't have any option element to add those attributes to, I can't find a way to do it.

My items look like:

{value:1,text:"Option 1",status:"finished"},{value:2,text:"Option 2",status:"running"},{value:3,text:"Option 3",status:"scheduled"}

The idea is to style the options in the select in a different way based on their status. So I want to achieve something like:

<v-autocomplete
    v-model="selectedItem"
    :items="items"
    :item-status="item.status">
</v-autocomplete>

Is this possible?


Solution

  • It sounds like what you need is to utilise the item slot available for v-autocomplete element.

    <template v-slot:item="{ item }">
      <div :class="getItemClass(item)">
        {{ item.text }}
      </div>
    </template>
    

    Instead of using a getItemClass(item) method, you can also keep the status: className pairings in an object inside component data/computed. The syntax will change to itemClass[item].

    The slot allows you to customise the list items in the dropdown. You can even use it to add different icons with different colours to represent the item statuses.

    You can create a similar template for the selection slot if you want a custom appearance when an item is selected.