Vue.js: 如何防止浏览器转到 href link 而只执行 @click 方法?
Vue.js: How to prevent browser from going to href link and instead only execute the @click method?
所以我的应用程序中有一个 link 是这样的:
<a href="/threads/my-first-thread/" @click="openThread">My first thread</a>
目前,当我点击 link 时,浏览器会跟随 href link 并执行 "openThread" 方法。我想将 link 保留在那里,以便它向用户显示点击会将他带到哪里,但我不希望浏览器实际跟随 link(我打开一个灯箱而是用 pushState 更改 url)。我希望它只执行给定的方法。
有什么办法吗?谢谢!
您正在寻找 .prevent 修改器。
<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
请参阅指南中的 Event Handling:
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
所以:
<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
<!-- -------------------------------------^^^^^^^^ --->
...或者当然,接受事件参数并调用 preventDefault.
Live Example on jsFiddle(因为 Stack Snippets 不允许站外链接)。
以防万一有人需要使用vue router
,这里是解决方案:
<router-link
:to="{ name: 'routeName' }"
:event="''"
@click="functionName"
>
所以我的应用程序中有一个 link 是这样的:
<a href="/threads/my-first-thread/" @click="openThread">My first thread</a>
目前,当我点击 link 时,浏览器会跟随 href link 并执行 "openThread" 方法。我想将 link 保留在那里,以便它向用户显示点击会将他带到哪里,但我不希望浏览器实际跟随 link(我打开一个灯箱而是用 pushState 更改 url)。我希望它只执行给定的方法。
有什么办法吗?谢谢!
您正在寻找 .prevent 修改器。
<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
请参阅指南中的 Event Handling:
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
所以:
<a href="/threads/my-first-thread/" @click.prevent="openThread">My first thread</a>
<!-- -------------------------------------^^^^^^^^ --->
...或者当然,接受事件参数并调用 preventDefault.
Live Example on jsFiddle(因为 Stack Snippets 不允许站外链接)。
以防万一有人需要使用vue router
,这里是解决方案:
<router-link
:to="{ name: 'routeName' }"
:event="''"
@click="functionName"
>