How to toggle active class inside v-for?

Harry Beckwith
Vue.js Developers
Published in
1 min readAug 2, 2019

v-for Vendetta 😄

Using v-for inside a template is pretty common within a Vue app. It can become tricky if you wanted to toggle an active class on the selected item only and not every item inside the loop. Let's see how…

Template app.vue

The above, we have a basic app.vue file template. A v-for looping over items with i set for the index. The class is then bound to active, only when the index is equal to the activeItem, will this equal true and produce the active class.

Data and methods

First, we set the activeItem data = null.

Then we change this data with the selectItem method, which takes the index as a parameter and updates the activeItem to match the index of the clicked item. Now when we click on the first item, activeItem = 0, i = 0, therefor the first item will be given the active class, and the other items will not.

A pretty simple solution but works well, if possible you can change the data being looped over and store a isActive key and value and toggle this way also.

Thank you ☕️

--

--