Implementing Vue JS to toggle a class on an item when it is clicked, and then removing the class when a sibling item is

When I click on a navigation list item, a class is added and then removed when clicked again. However, the class is being added to all items in the list instead of just one at a time. Additionally, I have a requirement where a click action should perform two tasks (scrolling and adding 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>

The methods used are:

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

scrollTo { This is working fine},

activeLink() {
            this.isActive = true;
        }

    }
});

I am seeking assistance to ensure that the class only applies to the currently active element.

Appreciate your help!

Answer №1

Simply pass the index to determine isActive state.

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

When you click, make sure to include the index.

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using TypeScript path aliases to resolve import errors

After creating a Vue.js project using Vue CLI 3 and setting up the import statement with the @ alias, I encountered an error when running npm run build. Can you explain why this happened? Error Message $ npm run build > [email protected] build / ...

What methods can I use to stop the styles of a child component from impacting those of the parent component

Is there a way to create CSS rules that achieve the following conditions? The parent component's CSS does not impact the child component The child component's CSS does not affect the parent component The child component is sourced from an exte ...

In JavaScript countdown timer, incorporate a leading zero to the minutes and seconds

I'm struggling to incorporate leading zeros into the minutes and seconds of this javascript countdown timer. I can't seem to make the leadingzero function work properly. The additional leadingzero function that I added doesn't appear to be f ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

The combination of Ajax and jQuery may unexpectedly produce an error even when everything seems to

I've been using AJAX with jQuery to call a script on the same domain. Everything was working perfectly - data being stored in the database, successful requests - until suddenly, I started getting errors. I even tried outputting JSON but it didn't ...

Conceptualization of a Strategy Game Server

Recently, I've been brainstorming the idea of developing a WebGL-based real-time strategy game that allows multiple players to join and play together. My plan is to utilize Node.js for creating the game server, along with websockets to establish real- ...

Constantly moving elements on the screen, teetering on the brink of entering the intersection when observed by the Intersection Observer

I'm facing a challenge with my sticky footer that contains stacked buttons. If the footer is not entirely in the viewport, I hide one of the buttons. When the footer is fully visible, all buttons should be shown. The issue arises when the container re ...

Tips for adjusting the background colors on the left and right sides of a page

Currently, I'm figuring out how to enhance the visual appeal of my website by altering the color scheme on both sides of the layout. Here's the snapshot of my struggle: https://i.sstatic.net/7Wkpc.png Here is a snippet of the key code used in my ...

A pair of demands within an express service

Currently, I'm facing an issue in a project where I am attempting to create a service using Express that makes two external API calls. However, I am encountering an error in Express that is difficult to comprehend. It seems like my approach might be i ...

Unexpected date outcomes in JavaScript when using a similar date format

Why is it that the first input produces the correct result, while the second input displays a time that is 5 hours behind? new Date("2000-1-1") Sat Jan 01 2000 00:00:00 GMT-0500 (EST) new Date("2000-01-01") Fri Dec 31 1999 19:00:00 GMT-0500 (EST) How can ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

What is the process for transferring form data from one HTML file and using it as a value in another?

Looking into jQuery to help with the following task. I have two HTML files, one containing a form and the other without. The aim is to transfer the full name inputted in the form from the first file to display it as the full name in the second file. Below ...

Mastering the art of counting down using a forEach loop in JavaScript

Trying to iterate through a list of objects, I can't index it, but can use forEach. My issue is I need to start from the last object and go to the first, but unsure how to achieve that with the forEach function. If I used a for loop, it would be like ...

Obtain the content of every cell in a constantly updating table

I have created a dynamic table as shown below: <table id="sort" class="table"> <thead> <tr> <th>Column Name from DB*</th> <th>Record Le ...

Injecting a torrent of PHP, HTML, and Javascript via AJAX to be displayed in the

Yesterday, I made the decision to dive into learning php, Javascript, and html. After writing a php script that worked perfectly when executed in php5 within the terminal, I attempted to integrate it into a webpage using Javascript. However, instead of dis ...

Ways to conceal ad container when ad space remains empty

After setting up my ad HTML like this: <div class="ad-container"> <p>Ad slot #1</p> <div id="ad-slot-1" class="ad-slot"></div> </div> I implemented the code below to collapse the ad if ...

"Be sure to add a table to the req.body information

Building on the topics of my recent inquiries about fetching data from async functions and adding IDs to checkboxes using loops on Stack Overflow, I am faced with a new challenge. I am attempting to retrieve the checked checkboxes using Node.js and Express ...

The type '{}' cannot be assigned to type 'IntrinsicAttributes & FieldsProp'. This error message is unclear and difficult to understand

"The error message "Type '{}' is not assignable to type 'IntrinsicAttributes & FieldsProp'.ts(2322)" is difficult to understand. When I encountered this typeerror" import { useState } from "react"; import { Card } fr ...

When trying to use routes with the .map() function, it does not seem

I am currently working on developing a multi-page web application using react-router-dom. However, I have encountered an issue with the user list page (userlist.js) where the data inside the .map() function is not being returned. Interestingly, the code pr ...

Tips for resolving undefined error handling in node.js

const fileSystem = require('fs'); const fileName = './prices.json'; const file = require(fileName); const price = require('./prices.json'); const fileName = './prices.json'; if(tmd = message.match(/^!change max ...