VueJS 将类切换到表中的特定元素 [英] VueJS Toggle class to specific element in table

查看:17
本文介绍了VueJS 将类切换到表中的特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can’t seem to figure out how to toggle a class on a specific item in a table. I’m using v-for to loop over the data and printing it out to the user. The goal is to toggle a class when the user clicks on a specific element inside the table. When i’m trying to add a v-bind:class="{'active' : isActive} it just adds that class to all of them and not the specific.

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

推荐答案

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

Any binding within an element using the v-for directive is going to apply to each element rendered by the v-for.

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

If only one element is to be active at a time, you could keep track of the active index:

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 对象本身上跟踪每个元素的活动状态:


If multiple elements could be active at a given time, you could keep track of each element's active status on the item object itself:

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

这篇关于VueJS 将类切换到表中的特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆