Slaveworx
Slaveworx

Reputation: 611

<router-link> Vue Router @click event

I tried using a click event on a <router-link>. It works, but it is reloading the page everytime the link is clicked. I would like to avoid it but I can't figure out how.

I am aware that <router-link> does not accept a simple @click event. I saw on some forums that @click.I native would work, but as we know, that is deprecated.

So I would like to know if there is any solution other than wrapping the router link in a div and putting the listener on that div.

The reason why I want to do this is that I want to bind a class dinamicaly when the link is clicked. I have created a dropdown menu which is triggered onClick. But then when I follow a link inside that dropdown menu, the menu remains open. Therefore, I would like to have an additional @click event to dinamically bind a class (display: none) to the dropdown menu. The thing is that the items inside the dropdown are iterated which send parameters to a Vuex Mutation and therefore i can’t use regular tags and wrapping the router-links with a span or div is also not giving me the desired effect.

Thank you !

Regards,

T.

Upvotes: 3

Views: 4468

Answers (2)

Slaveworx
Slaveworx

Reputation: 611

I have managed to solve the problem using a div wrapper and changing my css (that was preventing the code to work properly)

 <div class="dropdown">
        <a class="dropbtn" @click="dropClick"><i class="ri ico ri-draft-line"></i> Docs <i class="ri ico ri-arrow-drop-down-line ri-1x"></i></a>
        <div class="dropdown-content" :class="{ 'dropdown-content-display': clicked }">
          <div class="wrapper" v-for="route in $store.state.menuItems" :key="route.name" @click="dropClick">
            <router-link :to="{ name: 'docs', params: { title: route.name } }"> <i :class="'ico ri ' + route.icon"></i> {{ route.name }}
            </router-link>
          </div>
        </div>
      </div>

Upvotes: 2

Gurkan Ugurlu
Gurkan Ugurlu

Reputation: 467

If a understand your question, there is a "active-class" property on vue-router(router-link). You can set your classes dynamically by based on an active route.

Upvotes: 1

Related Questions