简体   繁体   中英

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('/'); 
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM