我在router-link
组件上有一些动态呈现的文本。代码是这样的:
<router-link :to="object.link" tag="div">
<span v-html="object.text"/>
</router-link>
object: {
link: "home",
text: "Click here to go to my homepage. Don't want that? Go to <a href="google.com">Google</a> instead."
}
按预期,单击div
/ router-link
将导航到对象的链接。但是,单击锚定词“ Google”也会导航到对象的链接,而不是预期的href
。
我希望这种行为是
div
或文本->导航到对象链接a
标签->导航至a
参考我可以通过停止在span
上的点击传播来实现第二个目标,但是然后单击非a
标签的文本不会激活router-link
。
如何实现这两种行为?
答案 0 :(得分:1)
在click
包装器上应用span
处理程序,该包装器为a
事件目标调用Event.stopPropagation
:
<template>
<router-link :to="object.link" tag="div">
<span @click="onWrapperClick" v-html="object.text" />
</router-link>
</template>
<script>
export default {
//...
methods: {
onWrapperClick(e) {
if (e.target.tagName === 'A') {
e.stopPropagation()
}
}
}
}
</script>
const Home = {
template: '#home'
}
const LinkDemo = {
template: '#linkDemo',
data() {
return {
object: {
link: '/',
text: `Click here to go to my homepage. Don't want that? Go to <a href="https://stackoverflow.com">StackOverflow</a> instead.`
}
}
},
methods: {
onWrapperClick(e) {
if (e.target.tagName === 'A') {
e.stopPropagation()
}
}
}
};
const routes = [
{ path: '', component: Home },
{ path: '/demo', component: LinkDemo }
]
const router = new VueRouter({
routes
});
new Vue({
router
}).$mount('#app');
<script src="https://unpkg.com/vue@2.6.10"></script>
<script src="https://unpkg.com/vue-router@3.1.3"></script>
<script type="text/x-template" id="home">
<div>
<h2>Home</h2>
<ul>
<li>
<router-link to="/demo">External Link Demo</router-link>
</li>
</ul>
</div>
</script>
<script type="text/x-template" id="linkDemo">
<div>
<h2>External Link Demo</h2>
<ul>
<li>
<router-link :to="object.link" tag="div">
<span @click="onWrapperClick" v-html="object.text" />
</router-link>
</li>
</ul>
</div>
</script>
<div id="app">
<router-view></router-view>
</div>