Elliot
Elliot

Reputation: 1616

Can I extend router-link?

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);
    }
  }
});

Upvotes: 0

Views: 1656

Answers (1)

stdob--
stdob--

Reputation: 29147

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/ ]

Upvotes: 2

Related Questions