2

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

1 Answer 1

6

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}"
>
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct! Thank you so much! Used way much time on this than i should. Have a great day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.