Back

Fixing active router link styling for subroutes in nuxt3

08. July, 2023

While creating the blog for this website, I noticed something strange.

When navigating to a subroute (for blog posts for example), the router doesn’t recognize the main route (”/blog” for example) as an active route. The solution for this is quite simple really. All you have to do is check, whether the current route contains the main route you are on right now:


1. Get the current route with useRoute()

vue
<script setup lang="ts">
    const route = useRoute()
</script>

2. Add the router-link-active class to your link when the path includes your route

vue
<NuxtLink 
    to="/yourRoute" 
    :class="route.fullPath.includes('yourRoute') ? 'router-link-active' : '' "
>
    Your Link
</NuxtLink>

I hope I could help someone with this little trick.

©2023 - 2024 Mathias Mantai