In my navigation bar, I have created 3 links which are all declared at the root level of the router object. I've applied some simple styling to highlight the active link on the navbar using the <router-link-active>
class. Everything works as expected - switching between links updates the URL, changes the <router-view>
, and applies the correct style to the currently active navbar link.
The issue arises when I click on a 4th link that is also declared at the root level of the router object, starting with the same path name as the currently active link. This causes the <router-link-active>
class to behave unexpectedly.
{ path: "/link2", component: link2 },
{ path: "/link2/sibling", component: sibling },
My understanding is that because the path /link2/sibling
starts with the same name as /link2
, the navbar item that navigates to /link2
should still have the <router-link-active>
class even when /link2/sibling
is the active URL.
Check out the Codesandbox for reference
App.vue
<template>
<div>
<ul class="flex gap-x-5">
<router-link to="/">
<li>Link 1</li>
</router-link>
<router-link to="/link2">
<li>Link 2</li>
</router-link>
<router-link to="/link3">
<li>Link 3</li>
</router-link>
</ul>
</div>
<router-view />
</template>
<script>
export default {
name: "App",
};
</script>
<style>
a:hover,
a:active,
a.router-link-active {
color: #f1a80a;
border-color: #f1a80a;
background-color: #1a037e;
}
</style>
main.js
import App from "./App.vue";
import router from "./router.js";
const app = createApp(App);
app.use(router);
app.mount("#app");
router.js
import { createRouter, createWebHistory } from "vue-router";
import link1 from "./components/link1.vue";
import link2 from "./components/link2.vue";
import sibling from "./components/sibling.vue";
import link3 from "./components/link3.vue";
const router = createRouter({
history: createWebHistory(),
routes: [
{ path: "/", component: link1 },
{ path: "/link2", component: link2 },
{ path: "/link2/sibling", component: sibling },
{ path: "/link3", component: link3 }
]
});
export default router;
link1.vue
<template>
<div>You are inside Link1</div>
</template>
link2.vue
<template>
<div>
<router-link to="/link2/sibling">
You are inside Link 2 (CLICK ME)
</router-link>
</div>
</template>
link3.vue
<template>
<div>You are inside Link 3</div>
</template>
sibling.vue
<template>
<div>You are inside Link2 sibling</div>
</template>