繁体   English   中英

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

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

所以我的应用程序中有一个链接,如下所示:

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

目前,当我单击链接时,浏览器会跟随 href 链接并执行“openThread”方法。 我想将链接保留在那里,以便向用户显示点击会将他带到哪里,但我不希望浏览器实际跟随链接(我打开一个灯箱并使用 pushState 更改 url) . 我希望它只执行给定的方法。

有没有办法做到这一点? 谢谢!

您正在寻找.prevent修改器。

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

请参阅指南中的事件处理

事件修饰符

在事件处理程序中调用event.preventDefault()event.stopPropagation()非常常见。 虽然我们可以在方法内部轻松地做到这一点,但如果方法可以纯粹是关于数据逻辑而不是必须处理 DOM 事件细节会更好。

为了解决这个问题,Vue 为v-on提供了事件修饰符。 回想一下,修饰符是用点表示的指令后缀。

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

所以:

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

...或者当然,接受事件参数并调用preventDefault.

jsFiddle 上的实时示例(因为 Stack Snippets 不允许站外链接)。

以防万一有人需要使用vue router ,这里是解决方案:

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

取自 vue-router git issue

暂无
暂无

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

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