Home > front end >  Prevent onclick event for parent when link inside is clicked in Vue
Prevent onclick event for parent when link inside is clicked in Vue

Time:05-28

I have a box as a parent element, and some elements inside parent. I want to be able to select this parent when clicked anywhere inside except that link. Link is working in my example, but the problem is that parent still gets selected...

<div  @click="select">
  <div >
  </div>
  <div >
    <a :href="google.com"  target="_blank">Go to...</a>
  </div>
</div>

v-on:click.stop, this solution was suggested for similar questions, but this is probably for elements like divs, paragraphs, etc...

CodePudding user response:

Have a look at Event Modifiers in the Vue.js docs here, v-on:click.stop will stop that click from propagating or "bubbling" up to the parent element.

This should work:

<a @click.stop :href="google.com"  target="_blank">Go to...</a>

If it doesn't work, then you can try something like this:

<div  @click="select">
   <div ></div>
   <div >
      <a @click.stop="goToUrl" >Go to...</a>
   </div>
</div>
methods: {
    goToUrl() {
        window.location.href = "https://www.google.com/";
    }
}
  • Related