【问题标题】:VueJS Toggle class to specific element in tableVueJS 将类切换到表中的特定元素
【发布时间】:2018-01-31 03:59:08
【问题描述】:

我似乎不知道如何在表格中的特定项目上切换类别。我正在使用 v-for 循环数据并将其打印给用户。目标是在用户单击表格内的特定元素时切换类。当我尝试添加 v-bind:class="{'active' : isActive} 时,它只是将该类添加到所有类而不是特定类。

<table>
     <tbody>
           <tr v-for="(item, index) in tableFilter"  @click="selectThis(item)" v-bind:class="{'active': isActive}">
                 <td>{{item.Name}}</td>
                 <td>{{item.Address}}</td>
                 <td>{{item.Telephone}}</td>
                 <td>{{item.Email}}</td>
            </tr>
     </tbody>
</table>

export default  {
    data() {
          return {
              isActive: false,
              data: data
          }
    },
    methods: {
          selectThis(val, index) {
              this.isActive =! this.isActive
          }
     },
    computed: {
       tableFilter() {
           return data;
       }
    }

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    使用v-for 指令的元素内的任何绑定都将应用于v-for 呈现的每个元素。

    如果一次只有一个元素处于活动状态,您可以跟踪活动索引:

    data() {
      return {
        activeIndex: null,
        data: data,
      }
    },
    methods: {
      selectThis(val, index) {
        this.activeIndex = index;
      }
    }
    

    改用它:

    <tr 
      v-for="(item, index) in tableFilter"  
      @click="selectThis(item)" 
      v-bind:class="{'active': activeIndex === index}"
    >
    

    如果多个元素可以在给定时间处于活动状态,您可以在 item 对象本身上跟踪每个元素的活动状态:

    <tr 
      v-for="(item, index) in tableFilter"  
      @click="item.active = !item.active" 
      v-bind:class="{'active': item.active}"
    >
    

    【讨论】:

    • 你是对的!太感谢了!在这方面使用的时间比我应该的要多。祝你有美好的一天:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多