[Router] Active Class on Submenu Parent

Given the following structure:

<ul class="nav">
  <li class="nav__dropdown">

    <ul class="nav-sub">
        <router-link tag="li" to="something" class="nav-sub__item">
          <a>Link</a>
        </router-link>
    </ul>

  </li>
</ul>

How can I add the active class on nav__dropdown (submenu parent) when I click on nav-sub__item (submenu item)?

Thanks for the help!

There’s no drect support for this in vue-router, so you have to build something on your own, foir example:

<li class="nav__dropdown" :class="{'router-link-active': subIsActive('/parent')}">
router-link-active
methods: {
  subIsActive(input) {
    const paths = Array.isArray(input) ? input : [input]
    return paths.some(path => {
      return this.$route.path.indexOf(path) === 0 // current path starts with this path string
    })
  }
}

now you can define an arbitrary path that should be matched, for example if all your submenus’ paths start with /products, you would do subIsActive('/products'). if some do start with /cart, you could do subIsActive(['/products', '/cart'])

10 Likes

Hey Linus, thank you very much.

have you solved this problem? I meet the same problem,thankyou

Appearantly, my provided solution worked for him. Do you have any specific questions about it?

Hello, Linus. Thank you for the support.

Your code works fine, but the first item of my menu is the parent route ("/"), so it is always active.
How can I archive something similar to exact-active-class?

A solution from the guys of Vue.js Brasil: https://jsfiddle.net/eywraw8t/383148/

I think the solution works well for making a parent active when a child item is selected.
The subActive method shouldn’t be called on all links.

Given what you have in your fiddle, a temporal fix is to apply/remove the active class when other router-links are clicked or selected.