[英]How to enclose a button in RouterLink, so that the navigation does not occur on button click
Let's say, I have the following markup:假设我有以下标记:
<RouterLink tag="div" to="/somepath">
<p>Lorem ipsum dolor sit amet.</p>
...
<button>A button</button>
</RouterLink>
I'm using tag="div"
, because nesting a <button>
inside an a
element is not valid HTML5 .我正在使用
tag="div"
,因为在a
元素内嵌套<button>
是无效的 HTML5 。
With this markup, clicking anywhere inside the RouterLink
, including a paragraph and a button, will cause navigation.使用此标记,单击
RouterLink
内的任意位置(包括段落和按钮)将导致导航。
But my requirement is that clicking on the button does not cause navigation, but clicking on other elements does.但我的要求是点击按钮不会导致导航,但点击其他元素会。
So, I use a div
with @click
handler that checks whether the clicked element is a button or its descendant and only navigates if not:因此,我使用带有
@click
处理程序的div
来检查单击的元素是按钮还是它的后代,如果不是,则仅导航:
<div @click="navigateSomewhere">
...
</div>
export default {
methods: {
navigateSomewhere($event) {
if(!$event.closest("button"))
this.$router.push("/somePath")
}
}
}
But I'm wondering if there is a cleaner way of doing this.但我想知道是否有更清洁的方法来做到这一点。
I have also created an MCVE: https://codesandbox.io/s/vue-routerlink-button-3dlyx .我还创建了一个 MCVE: https ://codesandbox.io/s/vue-routerlink-button-3dlyx。
<button @click.prevent="">A button</button>
这是因为按钮位于“点击区域”下,这意味着它不是可定位的,请尝试将相对位置和 z-index: 99 设置为按钮,并让我知道
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.