Christopher Adels
Christopher Adels

Reputation: 505

Vue 3 router - router-link-active not working

In vue 3 with router 4 the class router-link-active isn't working anymore for me. The class appears if u are on the same page, together with router-link-exact-active, but not on any subpages.

For example the link <router-link :to="{ name: 'test'}">test</router-link> get's the classes router-link-active and router-link-exact-active on /test but none of them on /test/2

{
    path: '/test',
    name: 'test',
    component: Test
},
{
    path: '/test/2',
    name: 'test-2',
    component: Test2
},

Real Example: https://codesandbox.io/s/vue-router-4-reproduction-forked-zcb7y

Thx, for any ideas or suggestions

Upvotes: 10

Views: 7801

Answers (2)

agm1984
agm1984

Reputation: 17188

I just had a problem here and it turned out to be caused by having the route declared twice in the routing file AND the <router-link> was using the second declaration in the routing file, so the active prop was not working when you clicked the link but it did work if you reloaded the page while on it.

This was true because when you reload the page, the correct route was matched due to vue-router loading the first matching route.

After I changed the router-link to use the correct route AND deleted the duplicate route.

My situation was a bit strange because it somehow worked, there was little evidence in the code until I started logging useRoute().name onto the screen and I noticed it had a different/incorrect name.

As a bonus, the article that was linked in the other answer was helpful in confirming everything was working as expected: https://github.com/vuejs/rfcs/blob/master/active-rfcs/0028-router-active-link.md#unrelated-but-similiar-routes

Upvotes: 1

Christopher Adels
Christopher Adels

Reputation: 505

I missed https://github.com/vuejs/rfcs/blob/master/active-rfcs/0028-router-active-link.md#unrelated-but-similiar-routes, it's a bit hidden. The shown RouterView workaround works fine. Here's it for my example:

import { h } from 'vue'
import { RouterView } from 'vue-router'

const routes = [
  {
    path: '/test',
    component: { render: () => h(RouterView) },
    children: [
      { 
        path: '',
        name: 'test',
        component: Test
      },
      { 
        path: '2',
        name: 'test-2',
        component: Test2
      }
    ]
  }
]

Upvotes: 27

Related Questions