What is the best way to dynamically apply the "active" class to a link when it is clicked

Here is how my vue component looks:

<template>
    <div>
        ...
        <div class="list-group">
            <a :href="baseUrl+'/message/inbox'" class="list-group-item">
                Message
            </a>
            <a :href="baseUrl+'/message/review'" class="list-group-item">
                Review
            </a>
            <a :href="baseUrl+'/message/resolution'" class="list-group-item">
                Resolution
            </a>
        </div>
        ...
    </div>
</template>
<script>
    export default {
        ...
        data() {
            return {
                baseUrl: window.Laravel.baseUrl
            }
        },
        ...
    }
</script>

After clicking a link and reloading the page, I want to add an 'active' class to that clicked link. However, I am unsure of how to achieve this. Can anyone provide guidance?

Answer №1

To achieve a dynamic styling effect, consider implementing a computed property named currentPath:

computed: {
  currentPath () {
    // Retrieve the current URL and extract the path after 'baseUrl'
    // For example, '/message/inbox' or '/message/review'
    return '/message/inbox'
  }
}

Add a CSS class for the unique style you desire:

.active-item {
  /* Add your specific CSS rules here */
}

In your template, assign the class to the corresponding item based on conditions:

<a :href="baseUrl+'/message/inbox'"
   :class="{ 'active-item': currentPath === '/message/inbox'}">
   class="list-group-item">Message</a>
<a :href="baseUrl+'/message/review'"
   :class="{ 'active-item': currentPath === '/message/review'}">
   class="list-group-item">Review</a>

For more information, refer to the documentation on binding HTML classes with object syntax

Answer №2

In addition to Leo's solution, consider implementing a component that can automatically detect its active state. This will eliminate the need for multiple <a> tags with redundant attributes.

Let's take an example of a <custom-link> component:

<custom-link href="/profile/settings" class="nav-item">
  Settings
</custom-link>
<custom-link href="/profile/edit" class="nav-item">
  Edit Profile
</custom-link>
<custom-link href="/profile/messages" class="nav-item">
  Messages
</custom-link>

If you do not plan on reusing this component or if the necessity of the nav-item class is consistent, you can also include it within the <custom-link>. This approach enhances readability:

<custom-link href="/profile/settings">Settings</custom-link>
<custom-link href="/profile/edit">Edit Profile</custom-link>
<custom-link href="/profile/messages">Messages</custom-link>

The code for the custom-link component may look like this:

<a
  :href="baseURL + href"
  :class="{ active: isActive }"
  class="nav-item"
>
  <slot></slot>
</a>

{
  props: ['href'],
  data: () => ({ baseURL: window.Laravel.baseURL }),
  computed: {
    isActive () {
      return location.href === this.baseURL + this.href
    }
  }
}

I have directly used location.href here, but you can opt for a computed property as per the need for any additional URL computations, just like in Leo's example.

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

Ideal JavaScript data structure for connecting three arrays

My goal is to establish a connection between three arrays in the following manner: arr1 = ['A', 'A', 'B', 'B', 'C', 'C' 'A', 'C'] arr2 = ['a', 'aa', ' ...

Passing individual state in Vuex as a parameter

Is there a way in Vuex to mutate two distinct states using the same function, without needing to repeat it for each state in the mutations section? Current approach: state: { firstparam:'', secondparam:'' }, mutations: { add ...

Terminate a targeted recipient following the completion of the on event

I am currently running a node service with socket.io and utilizing an event emitter to send updates based on user context. For example, context A may have users 1, 2, and 3 while context B has users 4 and 5. Once a successful connection is established wit ...

The child process is arriving empty, which is causing a requirement

Every time I try to use var childprocess = require('child_process'); I keep getting a blank result. When I attempt var childProcess1 = require('child_process').spawn; it returns as undefined, and, var childProcess2 = require(&a ...

What is the approach of Angular 2 in managing attributes formatted in camelCase?

Recently, I've been dedicating my time to a personal project centered around web components. In this endeavor, I have been exploring the development of my own data binding library. Progress has been made in creating key functionalities akin to those f ...

Creating a semi-circle donut chart with Highcharts using the Highcharts-ng library

I have been working on integrating a Highcharts Semi-circle donut chart into my angular application using the Highcharts-ng directive. However, I seem to be facing an issue where the plotOptions section is being skipped entirely, leading to a full circle p ...

Issues arise when attempting to incorporate the <style> tag in conjunction with requirejs and vue

I've been working on integrating a Vue app with an existing MVC application using require-js, require-vuejs, and vue-js. Everything was going smoothly until I encountered an error when trying to add a <style scoped> tag inside a component. If I ...

A guide on integrating the MUI Timepicker with the newest 6 version using Formik

I am currently experimenting with the MUI React Timepicker component and facing an issue during integration with Formik for validation. The problem lies in the inability to bind values properly in the initialValues of the form. const [initialValues, setI ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

Discovering the Vue.js API key within a Laravel application

Hey there, I'm facing an issue while trying to access my YouTube API key that is stored in the .env file from within this code snippet: <template> <div class="YoutubeDash__wrapper"> <video-group :videos="videos"></video- ...

Combining text output using JavaScript, HTML, and Vue

Can you help solve this challenge of outputting concatenated text from a javascript code? The script in question draws a quarter circle that is proportional to the size of the bar and showcases the value of pi accurate to three decimal places. To display ...

Make sure the "Treat labels as text" option is set to true when creating a chart in a Google spreadsheet using a script

I am currently working on a script using Google Spreadsheet Apps Script interface and I need to set the marker for 'Treat labels as text' to true. Despite searching through App Script documentation, I couldn't find any specific mention of t ...

Interested in creating a weather application that changes color based on the time of day

My attempt to create a weather app with a glowing effect has hit a roadblock. I want the app to glow "yellow" between 6 and 16 hours, and "purple" outside of those hours. I have assigned classes for AM and PM elements in HTML, and styled them accordingly i ...

Exploring the transparency of material lab autocomplete drop-down text for enabling multiple selections

Check out this demo for checkboxes and tags in Material UI The code below demonstrates an autocomplete component that functions correctly. However, the drop-down text appears transparent. Is there a way to fix this issue without modifying any libraries? ...

Receiving an error while trying to install packages from the NPM registry due to non

I am facing some challenges while attempting to install my Ionic App through the registry along with its dependencies. I have been using npm i --loglevel verbose command, and my ~/.npmrc file is configured as follows: //nexus.OMMITED.com/repository/:_auth ...

Harvesting information from an HTML table

I have a table displaying the following values: turn-right Go straight turn-left How can I extract only the 2nd value, "Go straight"? Here is the code snippet I tried: var text = $('#personDataTable tr:first td:first').text(); The code above ...

Designing dynamic SVG elements that maintain uniform stroke widths and rounded edges

I'm currently tackling a project that involves creating SVG shapes with strokes that adjust responsively to the size of their parent container. My aim is for these shapes to consistently fill the width and height of the parent container, and I intend ...

Form validation displaying only the initial error message

When validating a form, I am encountering an issue where only the first error message can be displayed: ContactUs.prototype.desktopErrors = function(){ var THIS = this; THIS.$el.find('#submit').on('click', function(){ ...

What steps can be taken to receive an alternative result when selecting a checkbox?

Currently, I am tackling the issue with checkboxes in Vuetify. The challenge lies in achieving a different output for the second {{ selected.join() }}. For example, when I select the checkbox labeled "Social Media," I receive the text "On our social medi ...

User authentication using .pre save process

I have an API that accepts users posted as JSON data. I want to validate specific fields only if they exist within the JSON object. For example, a user object could contain: { "email" : "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...