简体   繁体   English

Vue.js:如何防止浏览器转到 href 链接而只执行 @click 方法?

[英]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.目前,当我单击链接时,浏览器会跟随 href 链接并执行“openThread”方法。 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).我想将链接保留在那里,以便向用户显示点击会将他带到哪里,但我不希望浏览器实际跟随链接(我打开一个灯箱并使用 pushState 更改 url) . 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.在事件处理程序中调用event.preventDefault()event.stopPropagation()非常常见。 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.虽然我们可以在方法内部轻松地做到这一点,但如果方法可以纯粹是关于数据逻辑而不是必须处理 DOM 事件细节会更好。

To address this problem, Vue provides event modifiers for v-on .为了解决这个问题,Vue 为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. ...或者当然,接受事件参数并调用preventDefault.

Live Example on jsFiddle (since Stack Snippets don't allow off-site links). jsFiddle 上的实时示例(因为 Stack Snippets 不允许站外链接)。

Just in case if anyone needs to use vue router , here is the solution:以防万一有人需要使用vue router ,这里是解决方案:

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

Taken from vue-router git issue . 取自 vue-router git issue

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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