2
votes

I would like to highlight a table row on '@click' in Vuejs. Currently I'm having an issue getting this to work.

Here is my html template where I'm binding class active to the Boolean 'isActive'.

<table
      class="paginatedTable-table hide-table">
      <thead class="paginatedTable-table-head">
        <tr :class="{active: isActive}" class="paginatedTable-table-head-row">
          <th
            v-for="(column, key) in columns"
            :key="key"
            :class="column.align"
            class="paginatedTable-table-head-row-header"
            @click="sortTable(column)">
            {{ column.label }}
            <i
              v-if="sortOptions.currentSortColumn === column.field"
              :class="sortOptions.sortAscending ? icons.up : icons.down"
              class="sort-icon" />
          </th>
        </tr>

I'm declaring the isActive in the data function and setting to false.

data() {
    return {
      width: '100%',
      'marginLeft': '20px',
      rowClicked: false,
      filteredData: this.dataDetails,
      isActive: false,

Function for button click where I'm setting isActive to true

async selectRow(detail) {
      this.isActive = true;
      this.width = '72%';
      this.rowClicked = true;

This part I'm not so sure about. Here I'm setting the Css in Sass.

 tr:not(.filters):not(.pagination-row) {
      background-color: $white;
      &.active{
        background-color: $lc_lightPeriwinkle;
      }
2

2 Answers

8
votes

To iterate through a table of users, for example, and highlight a tr when clicked:

<table>
    <thead>
         <tr>
             <th>ID</th>
             <th>Name</th>
             <th>Email</th>
         </tr>
    </thead>
    <tbody>
         <tr v-for="user in users" @click="selectRow(user.id)" :key="user.id" :class="{'highlight': (user.id == selectedUser)}">
                <td>{{ user.id }}</td>
                <td>{{ user.name }}</td>
                <td>{{ user.email }}</td>
          </tr>
    </tbody>
</table>

Declare your data:

data(){
   return {
       users: [],
       selectedUser: null
   }
}

Inside your selectRow method;

selectRow(user){
    this.selectedUser = user;
    //Do other things
}

And then your class:

. highlight {
     background-color: red;
}
tr:hover{
     cursor: pointer;
}
0
votes

im late for the party, for vue 3 composition api version, in your table:

<tr v-for="(user, i) in users" @click="selectRow(i)" :key="i" :class="[index === i ? 'highlight' : '']">
            <td>{{ user.id }}</td>
            <td>{{ user.name }}</td>
            <td>{{ user.email }}</td>
      </tr>

then in:

setup : () => {
    const index = ref(null)

    const selectRow = (idx) => (index.value = idx)

    return { 
       selectRow, 
       index 
    }
}