Vue Event Modifiers

Vue Event Modifiers

In vanilla JavaScript, you frequently need to call event.preventDefault() or event.stopPropagation().

This prevents default browser behaviors, like forms refreshing the page upon submission.

Vue makes this incredibly easy by providing "Event Modifiers".


What are Event Modifiers?

Event modifiers are special postfixes appended to your v-on (or @) directives.

They are denoted by a dot (.).

They instruct Vue to handle the DOM event manipulation for you, keeping your methods purely focused on data logic.


The .prevent Modifier

The .prevent modifier is the most commonly used modifier in Vue.

It calls event.preventDefault() behind the scenes.

When attached to a <form> submit event, it stops the browser from reloading the entire page.

The .prevent Example:

<form @submit.prevent="submitForm">
  <button type="submit">Submit without reloading!</button>
</form>

Other Common Modifiers

Vue offers several other modifiers to control event propagation:


Key Modifiers

Listening for specific keyboard keys is also extremely common, especially the "Enter" key.

Vue provides Key Modifiers to easily listen for specific keystrokes.

You can chain the key name directly after the event, such as @keyup.enter.

Key Modifier Example:

<!-- Only fires submit() when the 'Enter' key is released -->
<input @keyup.enter="submit" />

Exercise 1 of 1

?

Which event modifier is used to stop a form submission from causing a full page reload?