Problem
Apply custom active class to active route in
nuxt-linktag 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>
...
The first choice is to use nuxt-link-active class to style the active route.
.nuxt-link-active {
font-weight: bold;
}
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;
}
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>
...
with the following css
.nuxt-link-active {
font-weight: bold;
}
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!
Top comments (4)
Works. Thanks.
Thank you for the article! I was facing the activated route styles issue for nested routes. The exact attribute fixed the issue.
Thanks, its saved my time ;)
Doesn't seem to work anymore? nuxt.com/docs/api/components/nuxt-... doesn't show any 'exact' prop and it doesn't seem to work