Home > other >  Vuejs How can I add a class to each row in the table
Vuejs How can I add a class to each row in the table

Time:11-01

I am having an html table as follows :

           <tbody>
                <tr
                  v-for="employee in employees"
                 :key="employee.EmployeeId"
                 @dblclick="rowOnDblClick(employee.EmployeeId)"
                 @click="rowOnClick(employee.EmployeeId)"
                 :class="{rowSelected: rowSelected.status}"
                 >
                    <td>{{employee.EmployeeCode}}</td>
                    <td>{{employee.FullName}}</td>
                    <td>{{employee.GenderName}}</td>
                    <td style="text-align: center;">{{employee.DateOfBirth|dateofbirth}}</td>
                    <td>{{employee.PhoneNumber}}</td>
                    <td :title="employee.Email">{{employee.Email}}</td>
                    <td>{{employee.PositionName}}</td>
                    <td>{{employee.DepartmentName}}</td>
                    <td style="text-align: right;">{{employee.Salary|money}}</td>
                    <td>{{employee.WorkStatus|status}}</td>
                </tr>
            </tbody>

Now I want every time I select a line that line is added class isActive
Tks so much

CodePudding user response:

Try like following snippet:

new Vue({
  el: '#demo',
  data() {
    return {
      employees: [{EmployeeId: 1, EmployeeCode: 1, FullName: 'aa bb', GenderName: 'm'},
      {EmployeeId: 2, EmployeeCode: 2, FullName: 'cc dd', GenderName: 'm'},
      {EmployeeId: 3, EmployeeCode: 3, FullName: 'ee ff', GenderName: 'm'}],
      selected: null
    }
  },
  methods: {
    rowOnClick(id) {
      this.selected = id
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
.active {
  background-color: orange;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <table>
  <tbody>
    <tr
      v-for="employee in employees"
     :key="employee.EmployeeId"
     @click="rowOnClick(employee.EmployeeId)"
     :class="selected === employee.EmployeeId && 'active'"
     >
      <td>{{employee.EmployeeCode}}</td>
      <td>{{employee.FullName}}</td>
      <td>{{employee.GenderName}}</td>
      <!--<td style="text-align: center;">{{employee.DateOfBirth|dateofbirth}}</td>
      <td>{{employee.PhoneNumber}}</td>
      <td :title="employee.Email">{{employee.Email}}</td>
      <td>{{employee.PositionName}}</td>
      <td>{{employee.DepartmentName}}</td>
      <td style="text-align: right;">{{employee.Salary|money}}</td>
      <td>{{employee.WorkStatus|status}}</td>-->
    </tr>
  </tbody>    
  </table>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related