【问题标题】:Vue.js - Change the class of a single table row in v-forVue.js - 在 v-for 中更改单个表格行的类
【发布时间】:2017-01-13 09:02:45
【问题描述】:

我正在显示使用 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);
  }
}

谢谢!

【问题讨论】:

    标签: javascript twitter-bootstrap vue.js


    【解决方案1】:

    success 类绑定到基于selectedCustomer 值的行应该可以帮助您实现所需的内容。像这样的东西,未经测试:

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

    【讨论】:

    • 非常聪明的答案! SO上的其他人建议跟踪父组件中的选定行,但这要简单得多。谢谢!
    猜你喜欢
    • 2018-08-07
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    相关资源
    最近更新 更多