I have some dynamically-rendered text on a router-link
component. The code is like this:
<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."
}
Clicking the div
/ router-link
will, as expected, navigate to the object's link. However, clicking the anchor word "Google" will navigate to the object's link as well instead of the intended href
.
I'd like the behavior to be:
div
or the text -> navigate to the object linka
tag -> navigate to the a
referenceI can achieve the second by stopping click propagation on the span
, but then clicking on the non a
-tag text doesn't activate the router-link
. How can I achieve both of these behaviors?
Apply a click
-handler on the span
wrapper that invokes Event.stopPropagation
for a
event targets:
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.