(Duplicate) Nuxt3 NuxtLink is not keeping router-link-active on parent link

360 views Asked by At
  1. 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>
  1. 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.

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>
0

There are 0 answers