Creating dynamic classes in Vue.js using methods based on conditions

Currently, I am working on setting an active/inactive link state in a navbar that is created using tailwind. To accomplish this, I am passing a prop based on the url (ActiveLink).

The goal is to implement something like the following:

<a href="/test" :class="{active(): ActiveLink == 'test', inactive(): ActiveLink !='test' }">Test</a>
<a href="/test2" :class="{active(): ActiveLink == 'test2', inactive(): ActiveLink !='test2' }">Test</a>

where the active/inactive methods return the necessary classes to be applied instead of manually specifying them like this:

<a href="/test" class="active">Test</a>
active() {
   return "px-3 py-2 rounded-md text-sm font-medium text-white bg-gray-900 focus:outline-none focus:text-white focus:bg-gray-700"
},
inactive() {
   return "mt-1 block px-3 py-2 rounded-md text-base font-medium text-gray-300 hover:text-white hover:bg-gray-700 focus:outline-none focus:text-white focus:bg-gray-700"
}

I believe that I may be taking the wrong approach with :class= but I haven't been able to discover a suitable alternative yet.

Answer №1

If you want to apply different classes based on multiple conditions in Vue.js, you can do so by using objects for binding classes. Here are a couple of ways to achieve this:

<a href="/test" :class="ActiveLink == 'test' ? 'active' : 'inactive'">Test</a>

Alternatively, you can use an array of class objects like this:

<a href="/test" :class="[{'active': ActiveLink == 'test'}, {'inactive': ActiveLink !='test'}]">Test</a>

By utilizing this approach, you can easily handle multiple classes with various conditions in your Vue.js application.

Answer №2

It is not necessary to repeatedly write the same condition. Just add the active class when required, leave it blank otherwise.

<a href="/test" :class="{'active': ActiveLink == 'test'}">Test</a>

Revision

After reviewing your feedback here, I have made some adjustments to meet your needs-

<a href="/test" :class="ActiveLink == 'test' ? active() : inactive()">Test</a>

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

Passing data from the controller to the $resource object in Angular with the MEAN stack

After several attempts to troubleshoot my issue with passing parameters to the Express server, it turns out the problem lies on the Angular side. When I manually inserted the id in the flConstruct.js function, the query worked correctly. It appears that ...

Do devDependencies get installed when running `npm install -g my-package` command?

After browsing through this forum discussion, I found the answers a bit confusing and not directly addressing my concern. Therefore, I am posing a specific question: When using the command npm install -g my-package, are the dependencies listed under devDe ...

Explanation requested for previous response about returning ajax data to the parent function

After coming across a helpful answer in the question titled How do I return the response from an asynchronous call?, I attempted to implement it without success. Reviewing Hemant Bavle's answer (currently with 62 votes) gave me hope, but my implement ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...

The response body in Superagent is unknown until the next line is executed

While working on testing my express API using Jest and Supertest, I encountered an issue that I cannot seem to resolve: const id = await request.post('/program') .send(body) .expect('Content-Type', /json/) .expect(201).body ...

What are the benefits of incorporating an external API with Next.js API routes?

I've recently started using Next.js and I'm curious about the purpose of export default function handler since we can directly fetch data from APIs. In my HTML code, I have the following snippet. When the submit button is clicked, the sendformDa ...

A-Frame: Capturing sweeping panoramic images with code

I am exploring panoramic screen shot capabilities and came across some documentation on how to take screenshots in A-Frame using hot keys. However, I am wondering if there is a method to generate a panoramic screenshot automatically without requiring user ...

What is the best way to send an HTML form variable to a Perl script using AJAX?

My goal is to pass the HTML variable from the list menu to the Perl script using POST. However, when I try to do this, the jQuery ajax() function executes the Perl script without including the value obtained from document.getElementById. Below is the sni ...

Unpredictable algorithm for selecting the champion

I manage a website that features promotions and users. Users have the ability to register for these promotions, with one random user selected as the winner. Initially, the formula for selecting the winner was quite simple: $total_users = 100; //total use ...

If one check box is selected, the other check box will automatically vanish

In my code snippet below, I have set up a section that functions as intended. However, I am encountering an issue where the shopping cart box remains even after deselecting the first checkbox. My goal is to have the top box act as the main controller, so i ...

I seem to be facing some issues while trying to create an avatar bot on discord.js

I'm trying to create a command for my bot that shows the user's avatar, but I keep running into an issue: DiscordAPIError: Cannot send an empty message at RequestHandler.execute (C:\Users\Pooyan\Desktop\PDM Bot Main\n ...

AngularJS directive failing to trigger event binding within the link function

Here is a plunker that you can refer to. In my project, I have developed two simple element directives, named incButtonOne and incButtonTwo. These directives are designed to track and display the number of times they have been clicked. Each directive has ...

utilize this within Vue methods to reference the item itself

Can you provide guidance on how to reference the element itself within functions using vue? For example: <div id="foo" onClick="clickFunction(this.id)"></div> In Javascript: function clickFunction(e){ console.log(e) // ...

I am having trouble getting the hamburger menu to open on my website with Bootstrap. Can anyone help me troubleshoot this issue and find

Why isn't my navbar hamburger menu opening on smaller screens? Despite the links displaying correctly on larger screens, I am unable to get the navbar to open. I've tried various troubleshooting methods such as changing tags in the header, deleti ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> S ...

Vue: Ensuring one method finishes executing before triggering the next one

I've implemented two methods in my Vue instance; const app = new Vue({ el: '#app', data: { id: null }, methods: { getId: function() { return axios.get('url') .then(response => response.data) .then(i ...

When the function is called, it will return the global `this

Attempting to bind the user object as 'this' and default time as the first parameter utilizing the function.call method let user = { name:'rifat', txt (time, msg){ console.log('['+time+ '] '+ this.name+ &apo ...

Stopping HTTP response in middleware using node.js and express - is it possible?

Currently, I am working on developing a timeout middleware using express in node.js. app.use((req, res, next) => { res.setTimeout(3000, () => { console.warn("We've reached the timeout limit - ending response with status code 408" ...

Enhancing a variable's value while simultaneously boosting its rate of increase through Javascript

Looking to adjust the timing on a number increase function using setInterval(Function, time). Initially set the variable for time as time = 1000, but now looking to dynamically change it by implementing a function triggered by a button click: function cha ...

What is the best way to swap out one component for another in a design?

I am working with a component that has the selector 'app-view', and I need to replace a specific part of the template: <div> content </div> The part that needs to be replaced will be substituted with another component: selector: &a ...