Search code examples
vue.jsvue-routerrouterlink

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.


Solution

  • 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.