我正在显示使用 v- for 动态生成的客户表。每行都有一个按钮,该按钮将客户ID添加到要发送到API的对象中。事情是,我想将Bootstrap .success类添加到单击的行中,以便用户知道已经选择了客户,但是我只能实现表中的所有行都获得.success类。另外,我希望当用户单击另一个客户时,所选客户会丢失.success类。
这是我的代码:

<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);
  }
}

谢谢!

最佳答案

根据success值将selectedCustomer类绑定(bind)到行应该可以帮助您实现所需的功能。像这样未经测试的东西:

<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>

07-27 14:45