Tips for styling links in Nuxt/Vue based on specific conditions

Struggling with conditional styling in my Nuxt app. I want to change the background color of the active link based on the current page. Using .nuxt-link-exact-active works for styling the active link, but how can I customize it for each page?

The links are in a component rendered on every page. I've tried using .nuxt-link-exact-active at the page level, but it doesn't work. My current code changes the styling based on the page, but it applies to all links instead of just the active one. Any clarification would be appreciated. Thanks!

<template>
  <nav class="flex-container flex-column mt-1">
    <NuxtLink to="/about" class="link" :class="classObject">about</NuxtLink>
    <div class="mt-1 flex-container">
      <NuxtLink to="/projects" class="link" :class="classObject"
        >projects</NuxtLink
      >
    </div>
    <div class="mt-1 flex-container">
      <NuxtLink to="/contact" class="link" :class="classObject"
        >contact</NuxtLink
      >
    </div>
  </nav>
</template>

<script>
export default {
  // apply current route name as a class to the matching div
  computed: {
    classObject() {
      return {
        about: this.$route.name === 'about',
        projects: this.$route.name === 'projects',
        contact: this.$route.name === 'contact',
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.about {
  background-color: $near-white;
}

.projects {
  background-color: $blue;
}

.contact {
  background-color: $yellow;
}
</style>

example of what I'm aiming for

Answer №1

If you want to modify the appearance of .nuxt-link-exact-active globally, it's better to do it in the layout rather than on individual pages.

For instance, you can make changes in the layouts/default.vue file like this:

<style>
.nuxt-link-exact-active {
  background: blue;
}
</style>

Answer №2

I devised a solution that may not be the most optimal, but it does the job. Now, every link is prefaced by a div element that will only appear on the designated page, while the link itself is displayed otherwise.

<template>
  <nav class="flex-container flex-column mt-1">
    <div v-if="currentPageName === 'about'" class="box about">
      <h2>about</h2>
    </div>
    <div v-else>
      <NuxtLink to="/about" class="link">about</NuxtLink>
    </div>
    <div v-if="currentPageName === 'projects'" class="box projects">
      <h2>projects</h2>
    </div>
    <div v-else>
      <NuxtLink to="/projects" class="link">projects</NuxtLink>
    </div>
    <div v-if="currentPageName === 'contact'" class="box contact">
      <h2>contact</h2>
    </div>
    <div v-else>
      <NuxtLink to="/contact" class="link">contact</NuxtLink>
    </div>
  </nav>
</template>

<script>
export default {
  computed: {
    currentPageName() {
      return this.$route.name
    },
  },
}
</script>

<style lang="scss" scoped>
.box {
  width: 150px;
  height: 150px;
}

.about {
  background-color: $near-white;
}

.projects {
  background-color: $blue;
}

.contact {
  background-color: $yellow;
}
</style>

Answer №3

If you're looking to verify the status of a path, one simple method is to use $nuxt.$route.path.

<template>
    <ul>
        <li>
          <nuxt-link :to="links[0].path" :class="{'bg-black text-white': links[0].path == path }">{{ links[0].name }}</nuxt-link>
          <nuxt-link :to="links[1].path" :class="{secondStyle: links[1].path == path }">{{ links[1].name }}</nuxt-link>
        </li>
    </ul>
</template>
    
<script>
    export default {
        name: "Header",
        data() {
          return {
            path: null,
            links: [
              {path: "/link1", name: "Link 1"},
              {path: "/link2", name: "Link 2"}
            ],
          };
        },
        mounted() {
          this.path = $nuxt.$route.path;
        },
    };
</script>

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

What could be the reason for the inconsistent behavior of onClick, causing it to occasionally fail to display the associated

I just started using typescript 2 days ago, mainly to create a custom component for my streamlit app. I've made a navigation bar with a tab that can be clicked on the sidebar, but it's displaying some erratic behavior. Sometimes when I click on t ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

"Despite not preferring to use the CORS wildcard, I am encountering a CORS wildcard error

I'm currently in the process of developing a web application using node, express, and Vue3 My goal is to submit a form to an endpoint located on my router at '/match/matchpost'. I have previously tested this endpoint successfully. However, ...

Press one button to activate another button

I am looking to activate a button's class by clicking on another button. The button I have is: <button class="clear-cart banner-btn">clear cart</button> This button is used for clearing a cart. On the order confirmation page, I click on ...

The CSS infinite animation becomes erratic and sluggish after a short period of time

My website featured a banner with a series of thumbnail images that animated at different intervals and looped indefinitely. Initially, the animations ran smoothly, but after a few seconds, they began to slow down and lose consistency. To troubleshoot, I u ...

Using Spring Boot RestController to Serve HTML Pages

I'm having trouble accessing the HTML page I created. Here is an overview of my project: This is the "IndexController" class: @RestController @AllArgsConstructor @RequestMapping(path = "/webpage") public class IndexController { @GetMapping(p ...

If the number of items in Vuetify tabs exceeds the limit, they will collapse into a 'more' button

I am working on developing an electron application with a customizable width, allowing users to adjust the size of the app according to their preference. The width of the app should determine how many "items" are visible in the navigation bar. If there a ...

Transforming Symbol Characters into HTML Using VB.NET

I want to make sure that any characters in my database entry that are not numeric or alphabetic get converted to HTML code. After doing some research, I came up with the following function: Public Shared Function HTMLEncodeSpecialChars(text As String) As ...

Prevent draggable function in jQuery-UI for specific elements

I'm in the process of creating a website that mimics a desktop interface, and I want to be able to easily move around the windows. To achieve this functionality, I am incorporating jQuery-UI along with the .draggable() method. My current HTML structur ...

Is there a way to showcase whitespacing in HTML?

I have a database full of content that includes whitespace formatting for display on a webpage. However, when viewed on Stackoverflow using the code tag, the formatting changes. The second way shows how it is stored in the database and how I want it to app ...

Troubleshooting Vue.js nested v-for with <tr> tag problem

Why does Vue complain about undefined properties when I try nesting a <tr> inside a <tr> with a v-for binding on each? <table> <thead></thead> <tbody> <tr v-for="item in items"> <td>{{ item.nam ...

Tips for adjusting the wrapper css rule of a Tabs component to left-align text in a vertical tab within Material-UI

Typically, when text is placed inside the wrapper, it is aligned in the center. Is there a way to adjust the wrapper rule in <span class="MuiTab-wrapper">Item One</span> so that the tab text is aligned to the left (similar to what w ...

Dealing with a passed EJS variable in string form

When working with passed data in ejs, I usually handle it like this and it works perfectly: let parsed_json = JSON.parse('<%-JSON.stringify(passed_data)%>'); However, I encountered a problem when trying to dynamically pass a string variabl ...

Class Background Imagery

Currently leveraging Wpbakery for my website design. Seeking to apply the FadeInUp animation solely to the background image rather than the entire row. Any suggestions on accomplishing this? Is there a method to assign a class solely to the background i ...

What is the best way to send a variable from a Vue view to a Laravel controller using InertiaJS in Laravel

How can I pass the 'CourseId' variable from a page view to a controller for deletion? I am having trouble accessing the variable: Page View: this.$inertia.get(this.route('applications.courseDelete', CourseId )) Route: Route::get(&apos ...

Is it possible for me to manually access the vue-router parser?

Is there a way to access the vue-router parser in order to evaluate a link before navigating to it? In other words: Suppose I have the path /one/two/three but it is not currently the active path. I would like to check if that path matches any defined rout ...

How to customize field appearance in Django authentication login view by adding a CSS class

I recently started working with Django and came across Django forms when using the django.contrib.auth.views.login view for user authentication. However, I'm struggling to figure out how to add a CSS class to the username and password fields. The doc ...

The display: table attribute is proving to be ineffective in creating the desired table layout. I am seeking alternative ways to

Is there a way to create a table using the CSS property display: table without utilizing the table element? I've searched for examples, but haven't found anything that has been helpful. Can someone please provide a fiddle of a table with a minimu ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

What is the purpose of "on" and "attrs" in Vuetify tooltips?

While exploring the Vuetify documentation, I came across an example for "Tooltip" that caught my attention: <v-tooltip left> <template v-slot:activator="{ on, attrs }"> <v-btn color="primary" dark ...