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

北城余情 提交于 2020-12-25 05:56:18

问题


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



来源:https://stackoverflow.com/questions/51223214/vue-js-how-to-prevent-browser-from-going-to-href-link-and-instead-only-execute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!