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

Encountering difficulties while using JavaScript to complete a form due to issues with loading the DOM

Currently, I am attempting to automate the completion of a multi-page form using JavaScript. Below is the script that I am utilizing: // Page 1 document.getElementById("NextButton").click(); // Page 2 completion(document.getElementById("Rec ...

When the React-bootstrap Popover arrow is oriented vertically, the arrow colors appear to be inverted compared to when it

Utilizing a react-bootstrap Popover component, I have implemented custom styling for the arrow with a gray color and 50% opacity. The CSS code that enables this customization is as shown below: .popover .popover-arrow::before, .popover .popover-arrow::afte ...

Steps to incorporate a personalized design onto a card element within Material UI

As a JavaScript developer, I was tasked by my brother to create a simple webpage for his business. Admittedly, frontend design is not my strongest suit so I decided to utilize Material UI and added some CSS to paste everything together. Right now, I am wo ...

There is an error in the regular expression that has not been caught: the forward slash is

I have a TableCell with the following structure: <asp:TableCell CssClass="plusTd button" ID="plusCell"> </asp:TableCell> Then, I decided to add a property to it like this: plusCell.Attributes.Add("onclick", "/Add.aspx ...

Design an interactive quarter-circle using CSS styling

My goal is to create this element using CSS, however, the content inside needs to be dynamic. I initially attempted to use border-radius, but realized it is unable to achieve the desired outcome. If anyone has a solution or can offer assistance, I would g ...

Toastr service experiencing issues on Internet Explorer browser

While implementing toastr notifications in my Angular application, I encountered an issue with compatibility across browsers. Specifically, the ngx-toastr module functions properly in Chrome and Firefox, but not in Internet Explorer. Interestingly, it wo ...

Behold the magic of a three-column layout with sticky scroll behavior and an absolute

I am struggling with a layout that involves 3 columns, each with its own independent scroll. The first column contains an absolute element that should overflow on the x-axis, but I am having trouble getting the overflow-x:visible property to work when comb ...

Issue with Bootstrap jQuery dynamic table edit/delete/view button functionality not functioning as expected

Could really use some assistance with this issue. I have a DataTable that includes a button in the last column which offers options like Edit/Delete/View. When clicked, it should delete the entire row. However, I'm struggling to access the current ele ...

Utilize Vuex store in Vue without the need for import statements within components

When working with Vue 2/3 and in an ES6 environment, I often access a Vuex store in an external JS file using the following method: // example.js import { store } from '../store/index'; console.log(store.state.currentUser); While this method w ...

Modifying arrays in Vue does not cause the DOM to update

I am facing an issue where I am trying to make modifications to an array in the parent component, which is passed down to the child component through Props. However, despite my efforts to insert and update data, the DOM does not reflect these changes. Par ...

JavaScript is unable to post content or access elements

Check out the following code: <div class="col-2"> <div class="input-group"> <label class="label">Name</label> <i ...

Generate a jQuery iframe once more by requesting it

How can I use jQuery to create an iframe tag and set it as the only content of a specific div? If the target div already has content, I want to replace it with a dynamically created iframe tag. This is what I have attempted so far: $(".someClass").click ...

javascript Why isn't the initial click registering?

In my table, users can select certain rows by using checkboxes. I have implemented some JavaScript functionality that allows them to select each checkbox individually and also use a "Select All" option. Additionally, there is code written to enable the use ...

Adjust the width of individual columns in Bootstrap 4 responsive tables to ensure they have specific widths

I am currently working on setting up a table where specific columns require a fixed width and do not adjust automatically. Despite attempting a method to achieve this, I have encountered issues as the width still adjusts based on the length of the text. ...

How to access the ID value from the URL within a different component that was passed as a prop in

I have a scenario where I am building a reusable component with two child components in the following flow: Child Component 1 -> Parent Component -> Super Parent Main Component In the child component, I define a prop called 'url' which is ...

Choosing the initial tab to display when the page loads from a selection of 3 tabs

How can I set the "All" tab to be selected by default when the page loads, with the text color black and underlined? .publisher-tab { background-color: rgb(255, 255, 255) !important; color: #B3B3B3; font-family: 'Open Sans'; font-style ...

Tips for sending information to a child component from a parent in Vue.js

Is there a way to pass the image url to this vue component? I am moving the code to a separate php file that will contain the <script> tag used by Vue, but it seems like it won't recognize the passed data from a parent component. Vue.component( ...

Creating a consistent base URL for both Vue and Apache reverse proxy configurations

Currently, I am experimenting with a Vue app and testing it using pm2 in conjunction with Apache. After starting the app with pm2 and running it on port 3000, I then utilize an Apache reverse proxy to access the app through a domain and HTTPS. However, I e ...

My initial junior UI/UX assignment: Can you confirm whether this form modal dialog is pixel-perfect, and offer any suggestions for improvements

Currently diving into my first project as a Junior UX/UI Designer. Coming from a background in software engineering, I decided to challenge myself by focusing on design. I'm seeking feedback on the pixel perfection of this modal window, which my seni ...

Building HTML tables with JQuery for handling large datasets of over 4,000 rows and beyond

My goal is to create a table with 4000+ rows and 18 columns displaying parsed pages from my site. I need it all on one page for the following reasons: I require the use of filters in the table I need to be able to sort by more than 5 columns Every cell ...