What is the best method for toggling a class to indicate the active tab in VueJS?

My goal is to set the active class on the first <li> tab by default, and then switch it to the second <li> tab when selected. I plan to use CSS to visually indicate which tab is currently active.

If you would like to see the current output, check out my JS Fiddle.

I would appreciate any assistance with this as I seem to be stuck.


<ul class="overlay-panel-actions-primary">
    <li v-for="(tab, index) in tabs" @click="currentTab = index">{{tab}}</li>
</ul>
<div class="content-bd">
    <div class="tab-content">
        <div v-show="currentTab === 0">
            List of filters options
        </div>
        <div v-show="currentTab === 1">
            List of sort options
        </div>
    </div>
</div>

new Vue({
  el: "#app",
    data() {
        return {
            currentTab: 0,
            tabs: ['Filter', 'Sort']
        };
    },
})

Answer №1

Here is a helpful code snippet -

:class="{active: currentTab === index}"

<li v-for="(tab, index) in tabs" @click="currentTab = index" :class="{active: currentTab === index}">{{tab}}</li>

If you try this out, please let me know if it works for you.

Fiddle link - https://jsfiddle.net/so3mf8h9/


An Update

Another way to achieve the same result is by using a ternary operator. You can give that a try as well.

:class="currentTab === index ? 'active' : ''"

Answer №2

Update: Oh, my mistake! I assumed you were utilizing vue-router. As your website grows, consider incorporating router functionality. Once you do, this method will be beneficial for you 🤓


Vue actually includes this feature 🙌

All you have to do is insert this code into your stylesheet

.router-link-exact-active {
    // Your styles go here
    border: 5px dashed red;
}

For more information, check out the Vue documentation

Here's how I applied it in a Vue site I created recently: Markup, and Styles. Let me know if you need any further assistance with implementing this 😊

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

The error persists in the Vee-validate regex rule despite having a successful match

Struggling with creating a regex to match a UUID - after validating it online and confirming that the regex is correct, vee-validate still shows it as an error. Any suggestions on how to fix this? <form @submit.prevent="performSearch"> ...

Browsing through a collection of pictures, I find myself wanting to linger on the final image rather than swiftly exiting the window

The functionality currently implemented is as follows: $("#btnNextImage").click(function (e) { var win = window.opener.parent; win.postMessage('next', '*'); window.close(); //close ...

Error encounter when loading the chunk for FusionCharts's overlappedbar2d.js in React.js: fusioncharts.overlapped

Currently, I am working on a web application that utilizes next.js and FusionCharts. Within the app, various FusionChart types have already been set up. My task now is to integrate the Overlapping Bars chart as outlined in the following documentation: How ...

Is there a way for me to determine if an image created with Image() has had its source modified?

Is there a way to track changes in the src attribute of images created using the Image constructor on a webpage without needing the image to be fully loaded? I have attempted to override the Image.onload method, but it does not log anything: Image.prototy ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

How to access a value from a for-loop in JavaScript beyond its scope

Hello there! Within nested json-files, I have been utilizing the following function for iteration: function organizePeopleGroups(People, container, parentObject) { _.each(People, function (item, index) { var peopleGuid =[]; for (var p ...

Encountering a high volume of requests error while attempting to retrieve data from the API using the NodeJS backend, yet functioning properly on the React

While attempting to retrieve data from https://api.solscan.io/chaininfo using a NodeJS backend application, I encountered an error stating 429: Too many requests. Interestingly, the same API functions without any issues when utilized in a React frontend a ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

Updating components reactively in Vue.js when a click event occurs

I have a dilemma with my component that allows users to add or remove an item from their favorites. While the functionality works smoothly, there is no visual indication for the user to know whether the item has been added to favorites or not. Currently, I ...

Error Encountered in NextJS - Hydration Unsuccessful

Currently, I am utilizing NextLink in my project to generate links. However, it appears that using NextLink is causing the following error: Hydration failed because the initial UI does not match what was rendered on the server. Upon inspecting the console ...

Uncertain about how to transfer data between server and client in Next.js?

I'm currently grappling with understanding the proper method of exchanging data between server-side and client-side components in NextJS 13. To simplify my learning process, I have created a basic scenario. In this setup, I have two functions that pe ...

Is it possible to perform a legitimate POST request using AJAX XMLHttpRequest, rather than the traditional var=val URL type post?

Apologies for the unclear question, but here is my query... I recently began using Ajax and encountered an issue with sending XMLHttpRequest in the background. I am facing problems with certain html special characters in the form data, especially the & ...

achieving bidirectional binding within a directive without using an isolated scope

One of my directives is set up like this: angular.module('somemodule').directive('tooltipText', function ($timeout, $compile, $document, config, $filter) { return { restrict: 'A', scope:{ tooltip: '=&ap ...

Tips for obtaining the sources of every image on a webpage and consolidating them in a single section

My goal is to preload all images on a webpage into a single division before the page loads. For example, if there are 5 images on the page (eg1.png, eg2.jpg, eg3.bmp, eg4.jpg, eg5.png), I want them to be contained within a div with the id 'pre'. ...

From transforming nested JSON into flat JSON structures within Javascript

Currently, I am faced with a challenge in my JavaScript programming. The task at hand is to transform the JSON data obtained from an API into a different structure while maintaining the essence of the original JSON. The existing JSON comprises members, num ...

Develop a personalized event that is compatible with all types of selectors

If I have a simple script that changes the background color of an element when clicked: $(".foo").on("change.color", function() { $(this).css("background-color", "red"); }); $(".foo").click(function() { $(this).trigger("change.color"); }); Currently ...

Encountering issues with loading a module in Aurelia

I've encountered a peculiar issue while attempting to load a module using Aurelia. The moment library was successfully loaded for date formatting, but when trying to load the numeral library in the same manner with npm install <module> --save, i ...

A guide to JavaScript: Fetching and Parsing JSON Data from an API

Hey there! I've been working on using this code snippet in my defult.js file to call an API, but I'm having trouble figuring out how to read the output. It always seems to end up in the last else part. function fetchDataDist(APPID, flag, call ...

Vue is alerting me that I cannot assign a reactive property to an undefined, null, or primitive value, specifically null

When retrieving data from Firebase, I am attempting to update the properties of the object being displayed on the UI. However, whenever I try to make any changes to the data, an error is thrown. Error in v-on handler: "TypeError: Cannot use 'in&apos ...