[Vuejs]-How remove active class from router-link when :to property get false value?

0👍

when you are in the same URL of router-link to the property, the element class will be active.

for example if you are in search page, following element class will be active:

<router-link to="/search"></router-link>

0👍

I came up with a solution. Based on this issue, vue-router doesn’t provide the disabled attribute, so you can use CSS to do the trick.

I tried to simulate your situation because I couldn’t see the result of your snippet. If it needs any update please let me know.

Vue.use(VueRouter)

const Name1 = {
  template: `<h1>Name1</h1>`,
}

const Name2 = {
  template: `<h1>Name2</h1>`,
}

const Name3 = {
  template: `<h1>Name3</h1>`,
}

const specificName1 = {
  template: `<h1>specificName1</h1>`,
}

const routes = [{
    path: '/name1',
    name: 'name1',
    component: Name1
  },
  {
    path: '/name2',
    name: 'name2',
    component: Name2
  },
  {
    path: '/name3',
    name: 'name3',
    component: Name3
  },
  {
    path: '/specific',
    name: 'specificName1',
    component: specificName1
  },
]

const router = new VueRouter({
  routes,
})
var app = new Vue({
  el: '#app',
  router,
  data() {
    return {
      routeName: 'specificName1',
      menu: [{
          to: 'link1',
          name: 'name1'
        },
        {
          to: 'link2',
          name: 'name2'
        },
        {
          to: 'link3',
          name: 'name3'
        },
        {
          to: 'specific',
          name: 'specificName1'
        }
      ]
    }
  },
})
a {
  color: black;
  text-decoration: none;
  padding: 1rem;
}

a.router-link-active {
  font-weight: bold;
  color: green;
  text-decoration: underline;
}

.disabled {
  pointer-events: none;
}
<script src="https://unpkg.com/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router"></script>

<!-- App -->
<div id="app">
  <nav>
    <router-link v-for="{ to, name } in menu" :key="name" :class="{disabled: (name === 'specificName1' || name === 'specificName2')}" :to="{name: name}">{{name}}</router-link>
  </nav>
  <router-view></router-view>
</div>

Leave a comment