Hillcow
Hillcow

Reputation: 979

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!

Upvotes: 6

Views: 11224

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075099

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).

Upvotes: 8

Aldarund
Aldarund

Reputation: 17621

You are looking for .prevent modifer.

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

Upvotes: 21

TitanFighter
TitanFighter

Reputation: 5094

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.

Upvotes: 1

Related Questions