Search code examples
javascriptvue.jsvuetify.js

How does one style a specific row on v-data-table? [Vuetify]


All I'm trying to do is for the given row that contains an entry that is equal to lowestEntry, change the background color.

<v-col cols="8">
        <v-data-table
          :loading="loadEntryTable"
          loading-text="A procurar dados..."
          :headers="this.entryheaders"
          :items="this.stockentries"
          :items-per-page="10"
        >
        //Have tried using the v-slot.item to achieve it but no success
</v-data-table>
</v-col>

I want to change the tr background color do green. Sort of highlight it when ìtem.id_entry == lowestEntry["id_entry"].


Solution

  • THIS ANSWER WAS ONLY FOR Vuetify 1 and Vuetify 2. If you are on Vuetify 3, you want this answer: https://stackoverflow.com/a/77716074/1206267

    If you're using newer versions of vuetify, you have access to item-class as a property of the v-data-table. This will provide the item as the first argument to the callback function.

    <v-data-table
    ....
    :item-class="itemRowBackground"
    ></v-data-table>
    

    And then define the function which will return the class name:

    methods: {
      itemRowBackground: function (item) {
         return item.protein > 4.2 ? 'style-1' : 'style-2'
      }
    }
    

    Then just define the classes for style-1 and style-2:

    .style-1 {
      background-color: rgb(215,215,44)
    }
    .style-2 {
      background-color: rgb(114,114,67)
    }
    

    Here's a code pen for this example that will work for you codepen example

    Edit If :item-class is not available for your current version of Vuetify, or you need more control over the row other than just binding a class, you'll have to use the item slot and bind the class/style/etc manually.

    Target the item slot and bind the class to the row manually:

    <v-data-table>
        <template #item="{ item }">
          <tr :class="item.id_entry === lowestEntry['id_entry'] ? 'custom-bg' : ''">
            <!-- manually define all of your <td> elements now. -->
          </tr> 
        </template>
    <v-data-table>
    

    Alternatively, you can pass :class="customRowClass(item, lowestEntry)" and define the customRowClass method:

    methods: {
      customRowClass (item, lowestEntry) {
      return item.id_entry === lowestEntry['id_entry'] ? 'custom-bg' : ''
      }
    }