Vue js Prevent on click on the parent when clicking a button inside div

Vue js Prevent on click on the parent when clicking a button inside div

·

2 min read

Hey Folks ! Have a look at Event Modifiers in the Vue.js v2 We can use the v-on directive to listen to DOM events and run some JavaScript when they’re triggered.

v-on:click.stop here is this @click.stop that will stop that click from propagating or "bubbling" up to the parent element.

Say you have a parent element and some child elements.

  1. 1st case you want the parent to click to does not affect the child clicks. Just put at the parent element the .self modifier:

take a look at this and try it how is this work

Child1 Child2 Child3

note: if you remove the .self when you click a child, the parent event will fire too.

2.2nd case You have the below code:

Click to activate

problem is

  1. When you click the icon element the parent click will fire. (you don't want this)
  2. You can NOT use the 1st solution because you want to fire the parent event even if the text "Click to activate" gets clicked.

The solution to this is to put the .stop modifier to the icon element so the parent event will not fire.

Vue js provides a few kinds of event modifiers

It is a very common need to call event.preventDefault() or event.stopPropagation() inside event handlers. Although we can do this easily inside methods, it would be better if the methods can be purely about data logic rather than having to deal with DOM event details.

  1. stop
  2. prevent 3.capture
  3. self 5.once
  4. passive

Did you find this article valuable?

Support ramu k by becoming a sponsor. Any amount is appreciated!