Event modifiers help control how events behave in Vue. They make it easy to stop events from doing their default actions or bubbling up, and to run handlers only once.
0
0
Event modifiers (prevent, stop, once) in Vue
Introduction
When you want to stop a form from submitting and refreshing the page.
When you want to prevent a click event from affecting parent elements.
When you want a button to respond only to the first click and ignore later clicks.
When you want to simplify event handling without writing extra code inside methods.
Syntax
Vue
<element @event.modifier="handler"> // Examples: <button @click.prevent="submitForm">Submit</button> <div @click.stop="handleClick">Click me</div> <button @click.once="doOnce">Click once</button>
Modifiers come after the event name, separated by a dot.
You can combine multiple modifiers like @click.prevent.stop.
Examples
This stops the default action, like page reload on form submit.
Vue
<button @click.prevent="submitForm">Submit</button>This stops the click event from bubbling up to parent elements.
Vue
<div @click.stop="handleClick">Click me</div>This makes the click handler run only once, ignoring later clicks.
Vue
<button @click.once="doOnce">Click once</button>Sample Program
This Vue component shows three examples:
- The form uses
@submit.preventto stop page reload. - The div uses
@click.stopto stop event bubbling. - The button uses
@click.onceto run the handler only once.
The message updates to show which event happened.
Vue
<template> <form @submit.prevent="onSubmit"> <button type="submit">Submit</button> </form> <div @click.stop="onDivClick" style="padding: 1rem; border: 1px solid #ccc; margin-top: 1rem;"> Click inside this box </div> <button @click.once="onClickOnce" style="margin-top: 1rem;">Click me once</button> <p>{{ message }}</p> </template> <script setup> import { ref } from 'vue' const message = ref('') function onSubmit() { message.value = 'Form submitted without page reload!' } function onDivClick() { message.value = 'Div clicked, event did not bubble!' } function onClickOnce() { message.value = 'Button clicked once!' } </script>
OutputSuccess
Important Notes
Use .prevent to stop default browser actions like form submission or link navigation.
Use .stop to prevent events from bubbling up to parent elements.
Use .once to make sure the event handler runs only the first time the event happens.
Summary
Event modifiers make event handling simpler and cleaner in Vue.
.prevent stops default browser behavior.
.stop stops event bubbling.
.once runs the handler only once.