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

1

8

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.

Radiotransparent answered 10/8, 2017 at 17:17 Comment(0)
B
20

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.
Baring answered 10/8, 2017 at 17:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.