Vue event modifiers prevent vs. stop
.prevent
or event.preventDefault()
– It stops the browsers default behaviour (A example is reload when you hit <button type="submit">
in <form>
)
.stop
or event.stopPropagation()
– It prevents the event from propagating (or “bubbling up”) the DOM
.once
- The event will be triggered at most once
Here is a practical example in VueJs 2:
var stopEx = new Vue({ el: '#stop-example', methods: { elClick: function(event) { alert("Click from "+event.target.tagName+"\nCurrent Target: "+event.currentTarget.tagName); } }})
#stop-example > div { max-width: 300px; min-height: 150px; border: 2px solid black; }
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script><div id="stop-example"> <h3>without stop propagation</h3> <div @click="elClick($event)"> <button @click="elClick($event)">Click Me</button> </div> <h3>with stop propagation</h3> <div @click="elClick($event)"> <button @click.stop="elClick($event)">Click Me</button> </div></div>
Here is how it works
On the first div element, (click) event for (div) element is handled by (div) and by the children of (div) because we did not stop propagation.
So once you click on button, the click event for button is triggered first then bubbling is done by moving on the ancestors of button.
The target is the element that handles the event while the currentTarget may be element that handles the event or ancestors of the element.
For this reason when you click on button on the first (div), the click event triggers twice due to handling click event of the parent.