0
votes

With Vue.JS, is it possible to extend router-link, or bind an event to it, such that for a particular type of link another action occurs?

What I would like to do is specify some links in my application to pop tabs, whilst others do not; e.g.

<router-link>no tab</router-link>
<router-link-tab>router view is updated and a tab is pushed</router-link-tab>

I would like to avoid binding an event to beforeRoute and inspecting for route urls, but appreciate that this might be the only way forward.

This needs to work across the Vue app, like router-link does, and will not be contained within only one component.

Am I going at this backwards? Would there be pitfalls in defining a custom component that triggered a new tab and called router.push, like this? Using RouterLink only to highlight active etc?

Vue.component('router-link-tab', {
  template: `<router-link :to="to" @click.prevent="click">
               <slot></slot>
             </router-link>
  `,
  props: {
    to: [String, Object],
  },
  methods:{
    click: function () {
        console.log(this.to);
        this.$router.push(to);
    }
  }
});
1
Similar, but I don’t think it’s the same. Where would the inline event handler be defined? My router-links are not all in the same component. - Kurucu
@stdob-- the second reason that this isn't a duplicate, is that the previous question looks at a single or few uses of adding an event listener. I'd like this to be global; to be defined once for all uses. - Kurucu

1 Answers

2
votes

You can use custom component:

Vue.component('router-link-tab', {
  template: `<router-link :to="to" event="" @click.native.prevent="click">
               <slot></slot>
             </router-link>
  `,
  props: {
    to: String,
  },
  methods:{
    click: function () {
        console.log(this.to)
    }
  }
});

[ https://jsfiddle.net/6dn8f1nw/ ]