Reputation: 113
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;
}
}
Upvotes: 2
Views: 2338
Reputation: 55644
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;
}
}
And use that instead:
<tr
v-for="(item, index) in tableFilter"
@click="selectThis(item)"
v-bind:class="{'active': activeIndex === index}"
>
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}"
>
Upvotes: 6