Instructions for adding a class when a li is clicked and replacing the previous class on any other li in Vue 2

Even though I successfully used jQuery within a Vue method to achieve this task, I am still searching for a pure Vue solution. My goal is to remove a class from one list item and then add the same class to the clicked list item. Below is the code snippet where I combined jQuery with Vue:

<ul class="manage-link">
    <li class="current 1" @click="run(1,'In progress')">Awaiting approval</li>
    <li class="2" @click="run(2,'In progress')">In progress</li>
    <li class="3" @click="run(3,'Completed')">Completed</li>
    <li class="4" @click="run(4,'Shipped')">Shipped</li>
    <li class="5" @click="run(5,'Delivered')">Delivered</li>
    <li class="6" @click="run(6,'Cancelled')">Cancelled</li>
    <li class="7" @click="run(7,'Under review')">Under review</li>
    <li class="pointer"></li>

</ul>

 methods: {
        run(num, str){
            console.log('ok');
            $(".manage-link>li").removeClass("current");
            $('.'+num).addClass('current');
        }
    }

In the above code snippet, the str variable serves another purpose unrelated to this specific issue. While the current implementation works as intended, my objective remains to accomplish the same outcome using only Vue.js. Thank you.

Answer №1

Implementing class bindings in Vue.js is incredibly straightforward!

<li class="1" :class="{current: current == 1}" @click="run(1)">Awaiting approval</li>
<li class="2" :class="{current: current == 2}" @click="run(2)">In Progress</li>
<li class="3" :class="{current: current == 3}" @click="run(3)">Completed</li>
<!-- repeat for more options -->

data () { // or simply "data:" if not a component
  return {
    current: 1
  }
},
methods: {
  run(num) {
    this.current = num
  }
}

Answer №2

One way to manage class manipulation is by passing the $event object in your click handler and handling it like so:

<ul class="manage-link">
    <li class="current 1" @click="run($event, 1,'In progress')">Awaiting approval</li>
    <li class="2" @click="run($event, 2,'In progress')">In progress</li>
    <li class="3" @click="run($event, 3,'Completed')">Completed</li>
    <li class="4" @click="run($event, 4,'Shipped')">Shipped</li>
    <li class="5" @click="run($event, 5,'Delivered')">Delivered</li>
    <li class="6" @click="run($event, 6,'Cancelled')">Cancelled</li>
    <li class="7" @click="run($event, 7,'Under review')">Under review</li>
    <li class="pointer"></li>

</ul>

 methods: {
    run(ev, num, str){
        console.log('ok');
        [].slice.call(ev.target.parentNode.children).forEach(function(child) {
            child.classList.remove('current');
        });
        ev.target.classList.add('current');
    }
}

Answer №3

To store the active element, you can utilize $index. For example:

<ul>
  <li 

<!-- begin snippet: js hide: false console: true babel: false -->

<ul class="manage-link">
    <li class="current 1" :class="{ active ? activeIndex === 1 }"@click="run(1,'In progress')">Awaiting approval</li>
    <li class="2"  :class="{ active ? activeIndex === 2 } @click="run(2,'In progress')">In progress</li>
    <li class="3" :class="{ active ? activeIndex === 3 } @click="run(3,'Completed')">Completed</li>
    <li class="4" :class="{ active ? activeIndex === 4 } @click="run(4,'Shipped')">Shipped</li>
    <li class="5" :class="{ active ? activeIndex === 5 } @click="run(5,'Delivered')">Delivered</li>
    <li class="6" :class="{ active ? activeIndex === 6 } @click="run(6,'Cancelled')">Cancelled</li>
    <li class="7" :class="{ active ? activeIndex === 7 } @click="run(7,'Under review')">Under review</li>
    <li class="pointer"></li>

</ul>

 data: {
  return {
    activeIndex: -1,
  };
 },
 methods: {
        run(num, str){
            this.activeIndex = num;
        }
    }

</ul>

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

Having trouble establishing a two-way binding between a Vue.js component and its model in the latest version 3.4.21

I am currently in the process of learning Vue.js, but I am facing issues with the code provided in the official documentation. Despite following the instructions, I keep encountering an error message from Vue stating: Property "PROPERTY_NAME" was ...

Tips for implementing Laravel authentication for an API while utilizing mongodb

For my latest project, I decided to develop a web app using Laravel, Vue.js, and MongoDB. When it came to creating the login functionality, I utilized the following code: <?php namespace App\Http\Controllers; use Illuminate\Http\R ...

Tips for dynamically updating the div class based on the model's value

How can I dynamically change the CSS class of a bootstrap element based on a value? I would like to display a div in green if the value is "OK" and red otherwise. If status = "OK", it should look like this: <div class="small-box bg-green">, else < ...

Navigating to the parent node in a treeview within the wijmo flex grid: a step-by-step guide

Utilizing the wijmo flex grid, I've successfully created a tree view for my data. I can determine if a specific node has children and its level, but I'm struggling to navigate to the parent node from a given one. Additionally, I am able to retrie ...

What's the best way to include CSS and Javascript in an HTML document?

I'm still getting the hang of CSS and JavaScript. I stumbled upon a cool countdown timer that I'd like to incorporate into my website, but I'm not quite sure how to place it where I envision it. Check out the timer here CSS: html,body{mar ...

"Encountering Issues with Angular's Modules and EntryComponents during Lazy Loading

Upon lazy loading an Angular module, I encountered an issue when trying to open my DatesModal that resulted in the following error: No component factory found for DatesModal. Have you included it in @NgModule.entryComponents? The declaration and entryCom ...

Tactics for postponing a js function post-click

I need to implement a delay after clicking a button to fetch some data. The code will be executed within the browser console. $(pages()) is used to retrieve the pagination buttons. let calls = []; for (let i = 1; i <= callPagesCount; i++) { ...

Tips for utilizing a button within a hyperlink in a React component:

I am new to react and have been working on the following code: import {NavLink as Link} from 'react-router-dom' return ( <div> {posts.map((actualData, index) => ( <Link to={'/' + actualData.id}> <d ...

Retrieve a snippet of code following the image URL on your web browser

While attempting to change the background image upon hovering, I encountered an interesting issue. The code for the image URL initially appears as follows: background-image: url('../assets/img/project1.png'); However, upon inspecting the co ...

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

Tabbed horizontal slider

I am trying to combine two scripts in order to create a tab-based system with a scrollbar located at the bottom of the content. I have merged the following Ajax tabs: with this slider: However, when I open the slider's tab, I am unable to move the s ...

Creating subtitles in a Quasar table: A step-by-step guide

Currently, I am working on using Vue3 with Quasar/cli. Is there a way to create category dividers (blue subtitles) using the Quasar component qTable or qMarkupTable? Check out this screenshot. I attempted to understand body slots, but unfortunately, I co ...

Numerous events have been successfully integrated into the angularjs-bootstrap-calendar

Currently, I am facing a challenge with loading all my event data from the server using angular-bootstrap-calendar. Due to the large volume of events, it is taking a considerable amount of time to load. I am exploring the possibility of fetching only a mo ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

Displaying a random number triggers a snackbar notification in a ReactJS application

Currently, I am utilizing the notistack package to display a snackbar on the screen. However, when calling the Snack component with enqueuesnackbar, a random number is displayed along with the snackbar. I'm looking to eliminate this random number fro ...

Replicate the anchor's functionality (opening in a new window when 'ctl' is pressed) when submitting a form

I have a question that may seem unconventional - Is there a graceful method to replicate the functionality of an anchor tag when submitting a form? I want users to be able to hold down the control key while submitting a form and have the result open in a ...

A comprehensive guide to using Reactive Forms in Angular

I need help understanding how FormGroup, FormControl, FormArray work in Angular. The error message I'm encountering is: Type '{ question: FormControl; multi: true; choices: FormArray; }' is not assignable to type 'AbstractControl' ...

Why have the bars been positioned on the left instead of the right, and why does the mobile version require sliding instead of simply accessing the menu through a function?

Hello everyone, I'm currently working on designing a mobile-friendly header menu with the bars positioned on the right side of the screen. The goal is to utilize JavaScript to allow users to click either an 'X' icon or the bars to open the m ...

Whenever I click on a button, I want to modify the background color of my react-modal

Having an array of images with clickable overlays and a modal that changes the background color based on the overlay name when clicked is the goal. However, passing this value as a prop proves challenging since the images are generated through a function a ...

Accessing a hyperlink in an alternative browser

Is there a way to transfer a link from one browser to another? For example, moving a link from Firefox to Chrome or from a Chrome Incognito window to a regular Chrome window. Let me provide more context. I have a webpage that refreshes every second and us ...