Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs <router-link> component keeps the link to the root path always active

I have my navigation like this

<nav>
    <ul class="nav nav-list">
         <router-link tag="li" to="/"><a href="#">Home</a></router-link>
         <router-link tag="li" to="/page1"><a href="#">Page1</a></router-link>
         <router-link tag="li" to="/page2"><a href="#">Page2</a></router-link>
    </ul>
</nav>

I want the link to Page1 to be active when ever am in page1 and same for Page2. It is working fine, the links are been activated when I navigate to the pages BUT the problem is that to link to the root (/) page is always active even when I leave the page.

like image 357
Kamga Simo Junior Avatar asked Aug 10 '17 17:08

Kamga Simo Junior


People also ask

How do I link my router to Vue?

To start with routing, we need to add the vue-router. js file. Take the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.

What is router link in Vuejs?

May 13, 2020. The router-link component creates an <a> tag that's configured to work correctly with Vue router.

How do I style a router link in CSS?

Create the header component that contains the navigation links. Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file. Provide the { exact : true } to the root route to avoid multiple active router links.

What is meta in route Vue?

Sometimes, you might want to attach arbitrary information to routes like transition names, who can access the route, etc. This can be achieved through the meta property which accepts an object of properties and can be accessed on the route location and navigation guards.


1 Answers

The root link is always active, because Vue Router partially matches the root / path with the current path.

To perform an exact match you can either:

  1. Add an exact attribute to the router-link:

    <router-link tag="li" to="/" exact>
        <a href="#">
            Home
        </a>
    </router-link>
    
  2. Set your active class in the linkExactActiveClass router constructor option instead of linkActiveClass.
like image 139
Kuba Szymanowski Avatar answered Oct 23 '22 06:10

Kuba Szymanowski