Max
Max

Reputation: 788

How to enclose a button in RouterLink, so that the navigation does not occur on button click

Let's say, I have the following markup:

<RouterLink tag="div" to="/somepath">
    <p>Lorem ipsum dolor sit amet.</p>
    ...
    <button>A button</button>
</RouterLink>

I'm using tag="div", because nesting a <button> inside an a element is not valid HTML5.

With this markup, clicking anywhere inside the RouterLink, including a paragraph and a button, will cause navigation.

But my requirement is that clicking on the button does not cause navigation, but clicking on other elements does.

So, I use a div with @click handler that checks whether the clicked element is a button or its descendant and only navigates if not:

<div @click="navigateSomewhere">
    ...
</div>
export default {
  methods: {
    navigateSomewhere($event) {
      if(!$event.closest("button"))
        this.$router.push("/somePath")
    }
  }
}

But I'm wondering if there is a cleaner way of doing this.

I have also created an MCVE: https://codesandbox.io/s/vue-routerlink-button-3dlyx.

Upvotes: 0

Views: 36

Answers (2)

Michal Lev&#253;
Michal Lev&#253;

Reputation: 37753

<button @click.prevent="">A button</button>

Upvotes: 1

Lafa
Lafa

Reputation: 523

It's becouse the button is under "the clicking area" that menas that is not targettable, try to set the position relative and the z-index: 99 to the button, and let me know

Upvotes: 0

Related Questions