Search code examples
javascriptvue.jsclasstoggleaddition

Vue JS add a class when an item is clicked and remove it when a sibling item is clicked


In a navigation list. I am having a class added on click, and it goes a way when I click again. It is adding the class to all the items of the list. I just wish to make one item active at a time on Click. Also, I have a click with two actions ( Scroll and then add a class)

<b-navbar class="d-flex flex-column align-items-start>
                    <b-navbar-brand tag="h3" class="m-0">List Index</b-navbar-brand>
                    <b-navbar-nav v-for="(linkItem, index) in linkItems" :key="index">
                        <b-nav-item :class="{ active: isActive }" class="pl-2" @click="scrollTo(`${linkItem.id}`), (isActive = !isActive)">
                            {{ linkItem.title }}
                        </b-nav-item>
                    </b-navbar-nav>
                </b-navbar>

And the methods are

data() {
        return {
            isActive: false,
            linkContent: [] as any
        };
    },

scrollTo { This is working fine},

activeLink() {
            this.isActive = true;
        }

    }
});

I need help making the class only apply to the active element.

Thanks


Solution

  • Just send index to isActive state.

    :class="{ 'active': isActive === index }"
    

    With click you must provide it's index

    @click="scrollTo(`${linkItem.id}`), (isActive = index)"