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.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay