Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js 3, vue-router, @click event reloads whole page

Im new to Vue and i want while on mobile navigation when I click menuItem I run function toggleMenu(open/close Menu), but then whole page reload, who to prevent that? This is my link:

 <router-link to="/" @click="toggleMenu">
    <div class="nav-item">Home</div>
  </router-link>

I tried adding @click.prevent and it prevents reload but not sending me to path.

EDIT:

So i make it works thanks to Boussadjra Brahim answer, but I did it with CompositionAPI and i used useRouter() hook from vue-router

Template:

 <router-link
  to="/"
  @click.prevent="toggleMenu">
  Home </router-link>

setup():

const router = useRouter();

function toggleMenu(){
   router.push('/'); 
}
like image 775
1haker Avatar asked Dec 21 '25 00:12

1haker


1 Answers

Add prevent modifier as you did then inside the toggleMenu add this.$router.push("/"); :

 <router-link to="/" @click.prevent="toggleMenu">
    <div class="nav-item">Home</div>
  </router-link>

LIVE DEMO

like image 109
Boussadjra Brahim Avatar answered Dec 23 '25 12:12

Boussadjra Brahim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!