Switch on/off the active class for menu items in a list using VueJS

When I click on a menu item, I want the active class to be triggered only for that specific item and removed for the others. So far, I have written this code:

<template>
  <nav class="navbar">
    <div class="navbar__brand">
      <router-link to="/">Stock Trader</router-link>
    </div>
    <div class="navbar__menu">
      <ul class="navbar__menu--list">
        <li @click="isActive=!isActive" class="navbar__menu--item" :class="{active:isActive}">
          <router-link to="/portfolio">Portfolio</router-link>
        </li>
        <li @click="isActive=!isActive" class="navbar__menu--item" :class="{active:isActive}">
          <router-link to="/stocks">Stocks</router-link>
        </li>
      </ul>
    </div>
    <div class="navbar__menu--second">
      <ul class="navbar__menu--list">
        <li @click="isActive=!isActive" class="navbar__menu--item" :class="{active:isActive}">
          <a href="#">End Day</a>
        </li>
        <li @click="isActive=!isActive" class="navbar__menu--item" :class="{active:isActive}">
          <a href="#">Save / Load</a>
        </li>
      </ul>
    </div>
  </nav>
</template>
<script>

    export default {
      data(){
        return{
          isActive: false

        }
      }
    }
</script>

Currently, clicking on any item adds/removes the active class for all items. What is the best approach to ensure that only the clicked item receives the active class?

Answer №1

Every clickable item needs a unique identifier assigned to its data property.

data() {
  return { selected: null }
}

When creating list items, ensure to set the identifier like this:

<li @click="selected = 'portfolio'"
    class="navbar__menu--item" 
    :class="{active:selected === 'portfolio'}">

In the above code snippet, the identifier used is "portfolio", however, any unique value can be used for each item.

Answer №2

To efficiently manage your navigation links, you can store them as objects and handle click events accordingly. For example:

data() {
  return {
    links: [
      {
        title    : 'Home',
        to       : '/',
        isActive : false,
        location : 'first',
      },
      {
        title    : 'About Us',
        to       : '/about',
        isActive : false,
        location : 'first',
      },
      {
        title    : 'Contact',
        to       : '/contact',
        isActive : false,
        location : 'second',
      },
      {
        title    : 'Services',
        to       : '/services',
        isActive : false,
        location : 'second',
      },
    ]
  };
},
methods: {
  handleNavClick(item) {
    this.links.forEach(el => {
      el.isActive = false;
    });

    item.isActive = true;
  }
},

Answer №3

In my Vue3 project, I implement the following template:

<li
  v-for="(title, index) in titles"
  class="title"
  :key="index"
  :class="{ active: active === index }"
  @click="updateActive(index)"
>
   {{ title }}
</li>

And here is the accompanying script:

<script lang="ts" setup>
import { ref } from "vue"
const titles = ["title1","title2","title3"]
const active = ref(-1)

function updateActive(val: number) {
  active.value = val
}
</script>

Answer №4

If you have multiple instances of ul, consider using title instead of index. For example:

<ul>
                <div>
                    Applicants
                </div>
                <li
                    v-for="(title, index) in applicantMenuTitles"
                    :key="index"
                    :class="{ active: active === title }"
                    @click="updateActive(title)"
                >
                    {{ title }}
                    <div
                        v-if=" active === title "
                        class="cursor"
                    />
                </li>
            </ul>
            <ul>
                <div>
                    Offices
                </div>
                <li
                    v-for="(title, index) in officeMenuTitles"
                    :key="index"
                    :class="{ active: active === title }"
                    @click="updateActive(title)"
                >
                    {{ title }}
                    <div
                        v-if=" active === title "
                        class="cursor"
                    />
                </li>
            </ul>
And in the script section:

...
const active = ref('')

function updateActive(title: string) {
    active.value = title
}

Answer №5

Presented here is a unique custom menu that remains active without dynamic menus. Its functionality is similar to that of Laravel.

       <li class="sidebar-dropdown" :class="$route.name === 'CategoryEdit' || $route.name === 'CategoryCreate' || $route.name === 'Categories' ? 'active' : ''">
          <a><i class="fa fa-cubes"></i> <span>Categories</span></a>
          <div class="sidebar-submenu" :class="$route.name === 'CategoryEdit' || $route.name === 'CategoryCreate' || $route.name === 'Categories' ? 'd-block' : ''">
            <ul>
              <li :class="$route.name === 'Categories' ? 'subactive' : ''">
                <router-link :to="{name: 'Categories'}">List</router-link>
              </li>
              <li :class="$route.name === 'CategoryCreate' ? 'subactive' : ''">
                <router-link :to="{name: 'CategoryCreate'}">Create</router-link>
              </li>
            </ul>
          </div>
        </li>

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

Why am I unable to make a selection in the dropdown menu?

Can anyone help me figure out why I am unable to select an option from the material ui library and display it in the state? Has anyone else encountered this issue? For a detailed code example, check here import React from "react"; import ReactDOM from " ...

Establish a many-to-many relationship in Prisma where one of the fields is sourced from a separate table

I'm currently working with a Prisma schema that includes products, orders, and a many-to-many relationship between them. My goal is to store the product price in the relation table so that I can capture the price of the product at the time of sale, re ...

Populate a form with database information to pre-fill the fields

So I have this web form built with HTML, and there are certain values within the form that can be changed by the user. To ensure these changes are saved, I'm storing them in a database. My goal is to have the form automatically filled with the data fr ...

Accessing data in a Vue template through a function call

I manage a network of stores that offer a wide range of products. I need the website to showcase a list of all the stores, along with the categories of products they sell. Having trouble displaying the product category list for each store <template ...

Prevent XHR from responding to OPTIONS method

Currently, I am in the process of developing an API that will be hosted on Azure functions and a Web App that will reside on Azure Blob storage. To ensure seamless communication between my API and the users' browsers, I have implemented proper handlin ...

Assign a CSS class individually to each item within a v-for loop

I've been experimenting with Vue.js and I'm attempting to dynamically change the class of specific items in a v-for loop based on a checkbox selection. <template> <div> <ul> <div :class="{completed: d ...

Comparing react-intl and react-i18next for internationalizing ReactJS applications

I am in the process of developing a multilanguage application using ReactJS. This application will require a custom dictionary for various languages, as well as automatic formatting for date/time, numbers, and currency. After researching, I have come acro ...

Discover how to extract a whole number (and *exclusively* a whole number) using JavaScript

Is it possible to convert a string to a number in a way that only integers produce a valid result? func('17') = 17; func('17.25') = NaN func(' 17') = NaN func('17test') = NaN func('') = NaN func('1e2& ...

Mastering angle calculations in three.js

My current task involves creating a series of arcs using 102 lines (start point, endpoint, and 100 curve points) However, I'm facing an issue when the start point of an arc has a higher value than the end point. For instance: Start Point: 359 End ...

Switching Profiles in XPages

In my Xpages project, I have two different user profiles set up. I am currently attempting to develop a function that would allow me to easily switch between these two profiles. However, I am unsure of the steps needed to accomplish this task. ...

The output of the http.get or http.request callback is only visible within the shell when using node.js

Just dipping my toes into node and aiming to avoid falling into the callback hell trap. I'm currently working with two files: routes.js fetch.js //routes.js var fetchController = require("../lib/mtl_fetcher/fetcher_controller"); var express = requir ...

Looking for an instance of a node.js ftp server?

I'm facing a challenge in creating a node.js application that can establish a connection with an FTP server to download files from a specific directory: Despite attempting to follow the instructions provided in the documentation for the ftp npm packa ...

What is the best way to send data from a React.js application to AWS Lambda?

I'm having trouble sending data from my React application to an AWS Lambda function through API Gateway. Here is the code snippet from my React app: const exampleObj = { firstName: 'Test', lastName: 'Person' }; fetch(process.env.R ...

What is the best way to preserve the status of a report when moving to a new component instance?

In my Vue application, I am using Vue version 3.1.31 and vue-router version 4.0.14. Within the application, there is a report consisting of multiple objects that can navigate to a new route where users can view or print a PDF of the information. However, ...

An issue occurred while attempting to retrieve an access token in NodeJs, resulting in 500 failures. The error message displayed was: "connect ECONNREFUSED" at process._tickCallback (node

I'm trying to authenticate users using Passport's GoogleStrategy, but I keep encountering the following error. Can anyone assist me? Code passport.use(new GoogleOAuth2Strategy({ clientID : configAuth.googleAuth.clientID, clientS ...

The functionality of the click and mousedown events seems to be disabled when using an Ajax form

Trying to create a simple Ajax popup featuring a form with 3 data fields and a submit button, however I'm unable to trigger the submit button programmatically. jQuery('#FormSubmit').click() seems to have no effect. The same goes for jQuer ...

Utilizing Restangular to refine search results with filters

I need help troubleshooting an issue with my Restangular query. Despite trying various methods, I am unable to retrieve filtered data successfully. Here are the different approaches I have attempted: $scope.welcomes = Restangular.all("projects").getList({ ...

sending numerous ajax requests and they all seem to be returning identical results

When firing multiple ajax requests using the setinterval() function, I noticed that both requests are bringing back the same information from another page. Here is the JavaScript code: function views() { setInterval(function(){var xmllhttp //alert ...

CoffeeScript and Node.js: Encountering an Unexpected ">" Token (Arrow Function)

After attempting to execute the following coffeescript, the issue arises: request = require('request') request('http://google.com', (error, response, body) -> if not error and response.statusCode is 200 console.log(body ...

Angular's FormGroup for reactive forms is a powerful feature that allows for

Why am I unable to type in the input field before setting a value? html <form action="" [formGroup]="titleForm"> <input class="note-title" type="text" formControlName="title"> </form> ...