Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify - How to highlight row on click in v-data-table

How to highlight the selected row in v-data-table? i tried to modified the data by adding flag variable selected in the Example

In the above example click on a row will be highlighted by adding class called primary. If it is a static data it is working fine, but if it is dynamic data like getting data from API, the data in the data table will always be refreshed, if i change the pagination and sort and all.

For example, in my case, if i sort the column the data will come from the API and data in the v-data-table will be refreshed with sorted data, in this case it is very hard to maintain that selected flag each and every time when ever the data changes. Is there any other way to highlight a selected row?

like image 498
Sam Avatar asked Jun 20 '19 13:06

Sam


People also ask

How do I highlight a row in a V data table?

In the above example click on a row will be highlighted by adding class called primary. If it is a static data it is working fine, but if it is dynamic data like getting data from API, the data in the data table will always be refreshed, if i change the pagination and sort and all.

What is V data table?

# Data tables The v-data-table component is used for displaying tabular data. Features include sorting, searching, pagination, content-editing, and row selection.


2 Answers

<v-data-table @click:row="rowClick" item-key="name" single-select ...

methods: {
    rowClick: function (item, row) {      
      row.select(true);
      //item.name - selected id
    }
}

<style>
  tr.v-data-table__selected {
    background: #7d92f5 !important;
  }
</style>

or

<style scoped>
  /deep/ tr.v-data-table__selected {
    background: #7d92f5 !important;
  }
</style>

Example https://codepen.io/nicolai-nikolai/pen/GRgLpNY

like image 97
Nicolai Nikolai Avatar answered Oct 16 '22 17:10

Nicolai Nikolai


Your solution does not work because the selected property is added to the data when you click on a row, but when data is reloaded then the data without a selected property replaces the old data.

So to make it work:
- add an id field to each item in the list of desserts
- add an selectedId with default value -1 to your data
- change the line of code in method activerow to this.selectedId = item.id;
- change the class attribute in the <tr> to :class="{'primary': props.item.id===selectedId}"

If on reload only your list of desserts changes, and the new list contains an item with the same id as selected before, then the same row should become selected.

I forked the codepen example to show you how this works:
https://codepen.io/anon/pen/PrWjxQ?editors=1010

like image 8
Sander_P Avatar answered Oct 16 '22 15:10

Sander_P