DEV Community

Cover image for Active class v-for
Harry J Beckwith
Harry J Beckwith

Posted on

Active class v-for

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

<template>
     <div>
        <div 
        v-for="(item, i ) in items" 
        :key="i"
        :class="{ active: i === activeItem}"
        >
         // some looped items from data here
         // button for active toggle 
            <button @click="selectItem(i)"> {{item}} make item active </button>
        </div>
    </div>
</template>
Enter fullscreen mode Exit fullscreen mode

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

<script>
export default {
    data() {
        return {
            activeItem: null,
            items: ['mike', 'chris', 'bob']
        };
    },
    methods: {
        selectItem(i) {
            this.activeItem = i;
        },
    },
};
</script>
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)