- I having an issue with nuxt link. The router-active-link class is not applies to the /course link when path is /course/123
This is my pages folder structure
- pages
- index.vue
- course/
- index.vue
- [id].vue
This is how I defined my app.vue
<template>
<div>
<NuxtLink to="/" class="link">Home</NuxtLink>
<NuxtLink to="/course" class="link">Course</NuxtLink>
<NuxtLink to="/course/123" class="link" exact>Course 123</NuxtLink>
<NuxtPage />
</div>
</template>
<style>
.link {
margin: 8px;
padding: 12px;
}
.link.router-link-active {
border: 1px solid red;
}
</style>
- I tried to do the hack with watching the route.path but it's not updating on click, only when I click twice on the link and this confuses me even more.
<script setup>
onst route = useRoute();
const activeRoute = ref(route.path);
watch(
() => route.path,
(route) => { activeRoute.value = route })
const activePath = (path: string) => {
return activeRoute.value.includes(path);
}
</script>
<template>
<NuxtLink to="/" class="link">Home</NuxtLink>
<NuxtLink
to="/course"
:class="{ 'router-link-active': activePath('/course') }"
class="link"
>Course</NuxtLink
>
<NuxtLink to="/course/123" class="link" exact>Course 123</NuxtLink>
</template>
Here is the stackblitz link https://stackblitz.com/edit/nuxt-starter-sdctyn?file=app.vue
~~Can someone explain why the router-link-active doesn't work as it should?~~
Answer is below
The solution you can find here.
- https://github.com/nuxt/nuxt/issues/20338
- https://router.vuejs.org/guide/migration/#removal-of-the-exact-prop-in-router-link
- router-link-active Nuxt 3 / VueJS on nested routes not applying to parent
But in short you need to rearrange the files in pages. Instead of
- pages
- index.vue
- course/
- index.vue
- [id].vue
It should be
- pages
- index.vue
- course/
- index.vue
- [id].vue
- course.vue
where course.vue contains
<template>
<NuxtPage />
</template>