Reading the Vue documentation about events, they mention the event modifiers like prevent or stop. They mention that on stop: <!-- the click event's propagation will be stopped -->
. I am assuming this will stop the event from bubbling. What about prevent
. What does it exactly do? I am assuming it will prevent the event from being triggered twice (on a double click for example). Are these assumptions correct? I just couldn't find more specific info on the web.
What I read:
Prevent default behaviorTo prevent an event's default behavior, we can call the . prevent modifier in Vue, which calls the native event. preventDefault() method. This series of steps prevents the event from reloading the page after the form is submitted.
preventDefault() or event. stopPropagation() inside event handlers. It is always better to have your methods deal purely with data logic instead of having to deal with DOM event details. Vue provides us with some event modifiers for the v-on.
self will prevent all clicks while @click. self. prevent will only prevent clicks on the element itself.
self. prevent will only prevent clicks on the element itself. Unlike the other modifiers, which are exclusive to native DOM events, the . once modifier can also be used on component events.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With