[Vuejs]-How to make vuejs navbar link active on click without route

1๐Ÿ‘

I had the same problem as you and solved it like this.

First, you define a method that will use the name property of this.$route

export default {
  name: 'App',
  methods: {
    getActiveNavLink(name) {
      //This is for the navbar classes, you can modify them as
      //as you need. (This will be assigned every-time we call this
      //function).
      let classString = "nav-item nav-link "
    
      //We compare the given name with the route current name.
      if (this.$route.name === name) {
        //If it is true, we append to the class string the "active" value
        classString += "active"
      }
      //Return the class string.
      return classString;
    }
  }
}

Then in your navbar you do something like this

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">The navegation bar</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNavAltMarkup">
      <div class="navbar-nav">
        <router-link 
          :to="{ name: 'home'}"
          :class="getActiveNavLink('home')" >
          Home
        </router-link>
        <router-link
          :to="{ name: 'secondRoute'}"
          :class="getActiveNavLink('secondRoute')"><!--class="nav-item nav-link">-->
          To the second route!
        </router-link> 
        <router-link :to=...>
          ...
        </router-link> 
      </div>
    </div>
  </div>
</nav>

That way, everytime you call the getActiveNavLink you pass the name of the route to compare, and if the name of the route is the same as your $route.name you will get an active navbar element!
Also, dont worry about the router-link classes being overwritten, they are not, the classes that we add, are appended, not overwritten.

0๐Ÿ‘

its works for me for add class attributte and methods calling

-1๐Ÿ‘

You could use router.push(). When you open the modal, push to that path, when you leave the modal, push to the previous path.

https://router.vuejs.org/guide/essentials/navigation.html

Leave a comment