Home > Back-end >  Is there a way I can nest a button inside of a router link, and when it's clicked to only trigg
Is there a way I can nest a button inside of a router link, and when it's clicked to only trigg

Time:12-03

To clarify, I have this router link inside a navbar, which has a button on top of it that changes the route.

Here's code for context:

<router-link v-if="foo" :to="/">
...
  <button @click="redirect"> GO </button>
...

The method for redirection:

redirect() { this.$router.push('/myroute').catch(() => {})

I tried using z index on both elements, but every time I click on the GO button it first goes to the '/myroute' and then goes back to '/'

Is there a way I can work around this?

CodePudding user response:

You could call event.stopPropagation() to prevent this event being propagated in the bubbling phase. So the event will stop only on the button element.

redirect(e) {
    e.stopPropagation();
    this.$router.push('/myroute').catch(() => {});
}

CodePudding user response:

You can use the stop modifier to @click.

<router-link v-if="foo" :to="/">
...
  <button @click.stop="redirect"> GO </button>
...

This is the vue equivalent of stopPropagation.

The z-index is more about the display of the button. Events propagate such that when you click on an inner DOM element, you're also clicking on everything that's at the (x,y) including the containing node. If there's nothing else listening to that event (which is usually the case) then the click does what you want.

Another alternative is to make the button and the router-link siblings, and use an outer <div></div> with some flex styling to place them where you want.

  • Related