vue路由器链接上的href链接

时间:2019-12-10 06:33:26

标签: vue.js vuejs2 vue-router

我在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。 如何实现这两种行为?

1 个答案:

答案 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>