Ektor Makras
Ektor Makras

Reputation: 1

Add conditional styles to v-data-table row

I am trying to apply a CSS class conditionally to a row of a v-data-table component. I saw the item-class prop does not exist in Vuetify 3, so the other solution that was commonly used is to utilize the default slot like this:

<v-data-table 
  :headers="tableHeaders"
  :items="tableItems"
  item-value="id"
>
  <!-- Default Slot -->
  <template #item="{ item }">
    <tr :class="{'bg-red': item.columns.temperature > 28}">
      <td
        v-for="header in tableHeaders"
        :key="header"
      >
        {{ item.columns[header.key] }}
      </td>
    </tr>
  </template>
      
  <!-- Temperature Slot -->
  <template #item.temperature="{item}">
    {{ item.columns.temperature }} &deg;C
  </template>
  
  <!-- Humidity Slot -->
  <template #item.humidity="{item}">
    {{ item.columns.humidity }} %
  </template>

  <!-- Id Slot -->
  <template #item.id="{item}">
    <v-btn
      @click="showInfo(item.columns.id)"
    >
      Show Info
    </v-btn>
  </template>
</v-data-table>
const tableHeaders = [
  {
    title: 'Temperature',
    sortable: true,
    key: 'temperature'
  },
  {
    title: 'Humidity',
    sortable: true,
    key: 'humidity'
  },
  {
    title: 'Info',
    sortable: false,
    key: 'id'
  },
]

const tableItems = [
  {
    id: 1,
    temperature: 22,
    humidity: 55
  },
  {
    id: 2,
    temperature: 30,
    humidity: 45
  },
  {
    id: 3,
    temperature: 22,
    humidity: 75
  },
]

The problem is this way my default slot overwrites the rest of the slots.

How can I conditionally apply a CSS class to rows in a Vuetify v-data-table while maintaining custom slots for other columns?

Upvotes: 0

Views: 1254

Answers (1)

Keyboard Corporation
Keyboard Corporation

Reputation: 2785

Your doing wrong here.

<tr :class="{'bg-red': item.columns.temperature > 28}">

Here how should it done. So I hope it helps.

Demo

Upvotes: 0

Related Questions