Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js - Change the class of a single table row in v-for

I am displaying a table of customers generated dynamically using v-for. Each row has a button that adds the customer ID in an object that will be sent to the API. The thing is, I want to add the Bootstrap .success class to the clicked row, so the user knows that the customer has been selected, but I can only achieve that all the rows in the table get the .success class. Also, I would like that when the user clicks another customer, the selected customer loses the .success class. Here's my code:

<table class="table table-responsive table-striped table-hover">
<tbody>
  <tr v-for="customer in customers">
    <td><button class="btn btn-default" v-on:click.prevent="selectCustomer(customer.id)"><i class="glyphicon glyphicon-ok"></i></button></td>
    <td>{{ customer.first_name }}</td>
    <td>{{ customer.last_name }}</td>
    <td>{{ customer.oib }}</td>
    <td>{{ customer.phone }}</td>
    <td>{{ customer.email }}</td>
    <td>{{ customer.street }} {{ customer.city }}, {{ customer.country }}</td>
  </tr>
</tbody>

export default {
data(){
  return {
    customers: [],
    selectedCustomer: ''
  }
},
methods: {
  selectCustomer(id, clicked){
    this.selectedCustomer = id;
    console.log(this.selectedCustomer);
  }
}

Thank you!

like image 656
bojan259 Avatar asked Sep 18 '25 03:09

bojan259


1 Answers

Binding success class to the row based on selectedCustomer value should help you achieve what you're looking for. Something like this, untested:

<table class="table table-responsive table-striped table-hover">
<tbody>
  <tr v-for="customer in customers" v-bind:class="{'success': (customer.id == selectedCustomer)}">
    <td><button class="btn btn-default" v-on:click.prevent="selectCustomer(customer.id)"><i class="glyphicon glyphicon-ok"></i></button></td>
    <td>{{ customer.first_name }}</td>
    <td>{{ customer.last_name }}</td>
    <td>{{ customer.oib }}</td>
    <td>{{ customer.phone }}</td>
    <td>{{ customer.email }}</td>
    <td>{{ customer.street }} {{ customer.city }}, {{ customer.country }}</td>
  </tr>
</tbody>
like image 146
Eric MORAND Avatar answered Sep 19 '25 18:09

Eric MORAND