简体   繁体   中英

Vue.js: How to prevent browser from going to href link and instead only execute the @click method?

So I have a link in my application like this:

<a href="/threads/my-first-thread/" @click="openThread">My first thread</a>

At the moment, when I click the link, the browsers follows the href link and also executes the "openThread" method. I want to keep the link in there so that it shows the user where a click is going to bring him to, but I don't want the browser to actually follow the link (I open a lightbox instead and change the url with pushState). I want it to only execute the given method.

Is there any way to do this? Thanks!

您正在寻找.prevent修改器。

<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>

See Event Handling in the guide:

Event Modifiers

It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers. Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

To address this problem, Vue provides event modifiers for v-on . Recall that modifiers are directive postfixes denoted by a dot.

.stop
.prevent
.capture
.self
.once
.passive

So:

<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
<!-- -------------------------------------^^^^^^^^                    --->

...or of course, accept the event parameter and call preventDefault.

Live Example on jsFiddle (since Stack Snippets don't allow off-site links).

Just in case if anyone needs to use vue router , here is the solution:

<router-link
  :to="{ name: 'routeName' }"
  :event="''"
  @click="functionName"
>

Taken from vue-router git issue .

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