1

I have link something like this:

 <li class="list-item active"> <router-link :to="{name:'link-1'}"> Link 1</router-link>
 <li class="list-item"> <router-link :to="{name:'link-2'}"> Link 2</router-link> 

I want to add class active with list-item class based on the url suppose if the url is localhost:8000/link-1 then link-1 should be active.

2 Answers 2

3

If you are using Vue Router > 3.1.0 you can use <router-link> and a scoped slot for this:

<router-link
  :to="{name:'link-1'}"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'active', isExactActive && 'exact-active']"
  >
    <a :href="href" @click="navigate">Link 1</a>
  </li>
</router-link>

<router-link
  :to="{name:'link-2'}"
  v-slot="{ href, route, navigate, isActive, isExactActive }"
>
  <li
    :class="[isActive && 'active', isExactActive && 'exact-active']"
  >
    <a :href="href" @click="navigate">Link 2</a>
  </li>
</router-link>

If you don't need to have .active on the li elements, <router-link> has this build in. (See Dan's awnswer)

Sign up to request clarification or add additional context in comments.

Comments

2

Vue router provides this functionality. When a link is active, it will have the router-link-exact-active class applied.

In your CSS:

.router-link-exact-active {
  // styles here
}

There is also router-link-active which would match both "/" and "/link-1".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.