Nuxt: How to use nuxt-link-active and nuxt-link-exact-active classes with nuxt-link?

drraq

Rehan Qadir

Posted on May 13, 2020

Nuxt: How to use nuxt-link-active and nuxt-link-exact-active classes with nuxt-link?

Problem

Apply custom active class to active route in nuxt-link tag including all nested routes

Let's say you wish to apply custom active class to an active route in nuxt-link tag.

...
<nav>
    <nuxt-link to="/">Home</nuxt-link>
    <nuxt-link to="/explore">Explore</nuxt-link>
    <nuxt-link to="/about">About</nuxt-link>
</nav>
...
Enter fullscreen mode Exit fullscreen mode

The first choice is to use nuxt-link-active class to style the active route.

.nuxt-link-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode
Discrepancy

If user navigates to /explore or /about route, the styling will get applied to / route as well which in practice is not desired.

Well, to resolve this issue one is prompted to use nuxt-link-exact-active along similar lines.

.nuxt-link-exact-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

Apparently this approach resolves the issue very well. But hold on, what if there are some nested routes? What about /explore/express or /explore/ruby-on-rails?

In practice if user navigates to any of the nested routes /explore should continue to have the styling, right? but with just nuxt-link-exact-link class in hand it will fail to persist.

Solution

To get the best of both worlds, use nuxt-link-active class along with exact keyword in nuxt-link tag.

Use exact in the nuxt-link tag

...
<nav>
    <nuxt-link to="/" exact>Home</nuxt-link>
    <nuxt-link to="/explore">Explore</nuxt-link>
    <nuxt-link to="/about" exact>About</nuxt-link>
</nav>
...
Enter fullscreen mode Exit fullscreen mode

with the following css

.nuxt-link-active {
    font-weight: bold;
}
Enter fullscreen mode Exit fullscreen mode

For every nested explore routes, /explore will continue to have the styling. Furthermore, / and /about will have the styling only when the exact route matches.


I hope it will help you. Keep coding!

💖 💪 🙅 🚩
drraq
Rehan Qadir

Posted on May 13, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related