lukas_o
lukas_o

Reputation: 4246

Vue event modifiers prevent vs. stop

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:

Upvotes: 40

Views: 38460

Answers (2)

Abdullrahman Qutaiba
Abdullrahman Qutaiba

Reputation: 177

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.

Upvotes: 9

Quoc-Anh Nguyen
Quoc-Anh Nguyen

Reputation: 5066

.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

Upvotes: 55

Related Questions