I would like to change the background color of the selected row in a v-data-table.
<v-data-table dense :headers="headers"
:items="records"
@click:row="handleClick"> <!-- handleClick is a function that logs item for the moment... -->
<template v-slot:[`item.index`]="{item}">
<v-row justify="center">
<v-col>
<div>{{item.index}}</div>
</v-col>
</v-row>
</template>
<template v-slot:[`item.status`]="{ item }">
<v-row justify="center">
<v-col v-if="item.status===1">
<v-icon color="green">
mdi-check-circle
</v-icon>
</v-col>
<v-col v-else>
<v-icon color="orange">
mdi-progress-check
</v-icon>
</v-col>
</v-row>
</template>
</v-data-table>
I couldn't find a way to distinguish the selected row from the others and thus update the style for the selected one.
Basically i'd like to reproduce the behavior implemented for the v-list component.
CodePudding user response:
Selected rows have the v-data-table__selected
class applied on their TR tag - so you can just create some CSS override to target them. The default style in Vuetify is
.theme--light.v-data-table tbody tr.v-data-table__selected
{
background: #f5f5f5;
}
CodePudding user response:
You can use item-key="index"
and single-select
to select row and set class tr.v-data-table__selected
:
new Vue({
el: '#app',
vuetify: new Vuetify(),
data() {
return {
headers: [{text: 'index', value: 'index'}, {text: 'status', value: 'status'}],
records: [{index: 1, status: 1}, {index: 2, status: 0}, {index: 3, status: 1}],
selected: null
}
},
methods: {
handleClick(item, row) {
row.select(true);
this.selected = item
}
}
})
tr.v-data-table__selected {
background: lime !important;
}
<link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<div id="app">
<v-app>
<v-main>
<v-container>
<div>{{ selected }}</div>
<v-data-table dense :headers="headers"
:items="records" item-key="index" single-select
@click:row="handleClick">
<template v-slot:[`item.index`]="{item}">
<v-row justify="center">
<v-col>
<div>{{item.index}}</div>
</v-col>
</v-row>
</template>
<template v-slot:[`item.status`]="{ item }">
<v-row justify="center">
<v-col v-if="item.status===1">
<v-icon color="green">
mdi-check-circle
</v-icon>
</v-col>
<v-col v-else>
<v-icon color="orange">
mdi-progress-check
</v-icon>
</v-col>
</v-row>
</template>
</v-data-table>
</v-container>
</v-main>
</v-app>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>