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.

Dev Diairies image

User Feedback & The Pivot That Saved The Project ↪️

We’re following the journey of a dev team building on the Stellar Network as they go from hackathon idea to funded startup, testing their product in the real world and adapting as they go.

Watch full video 🎥

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

👋 Kindness is contagious

Explore this insightful write-up embraced by the inclusive DEV Community. Tech enthusiasts of all skill levels can contribute insights and expand our shared knowledge.

Spreading a simple "thank you" uplifts creators—let them know your thoughts in the discussion below!

At DEV, collaborative learning fuels growth and forges stronger connections. If this piece resonated with you, a brief note of thanks goes a long way.

Okay