问题
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!
回答1:
You are looking for .prevent modifer.
<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
回答2:
See Event Handling in the guide:
Event Modifiers
It is a very common need to call
event.preventDefault()
orevent.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).
来源:https://stackoverflow.com/questions/51223214/vue-js-how-to-prevent-browser-from-going-to-href-link-and-instead-only-execute