Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent event bubbling in Vue

<div id="largeArea" v-on:click="do_X">     <button>Button</button> </div> 

So I have this issue in Vue where I don't want "do_X" to trigger when I click on the button, although its a part of the largeArea.

like image 982
eozzy Avatar asked Feb 15 '18 00:02

eozzy


People also ask

How do I stop event bubbling Vue?

We can prevent the click event from propagating to the parent when clicking a button inside an element with Vue. js with the self modifier. We add the self modifier to the @click directive on the outer div so that the click event will be confined to the parent div.

What is click stop Vue?

prevent is a modifier for v-on:click . Another handy modifier is . self , which tells Vue to only evaluate v-on:click if the element itself is clicked, as opposed to one of its children. For example, Vue only calls the below v-on:click handler when you click on the outer div , not the inner div .

How do you fix event bubbling?

If you want to stop the event bubbling, this can be achieved by the use of the event. stopPropagation() method. If you want to stop the event flow from event target to top element in DOM, event. stopPropagation() method stops the event to travel to the bottom to top.

What is disable click event bubbling?

Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. event.preventDefault() Prevents the browser from executing the default action.


2 Answers

I found that using the 'stop' event modifier on the child element worked for me. eg

<div id="app">   <div id="largeArea" @click="do_X">     <button @click.stop="do_Y">Button</button>   </div> </div> 
like image 164
omarjebari Avatar answered Sep 21 '22 23:09

omarjebari


From the documentation, use the self event modifier to only capture events originating on the element itself.

<div id="largeArea" v-on:click.self="do_X"> 

new Vue({    el: '#app',    methods: {      do_X () {        console.log(Date.now(), 'do_X')      }    }  })
#largeArea {    padding: 20px;    border: 1px solid black;  }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>  <div id="app">    <div id="largeArea" @click.self="do_X">      <button>Button</button>    </div>  </div>
like image 38
Phil Avatar answered Sep 23 '22 23:09

Phil