Event Handling (v-on & Modifiers)

💚 Vue.js Lesson 7 Beginner

The v-on directive (shorthand: @) listens to DOM events, triggering component methods or running inline JavaScript expressions when fired.

1 Event Modifiers

Vue provides event modifiers to handle common event actions without manual JavaScript overrides:

  • .stop: Calls event.stopPropagation() to prevent the event from bubbling up the DOM tree.
  • .prevent: Calls event.preventDefault() to block default browser actions (like form submissions reloading the page).
  • .once: Triggers the event handler at most once.
  • Key Modifiers: Listen for specific key triggers (e.g. @keyup.enter, @keyup.esc).
2 Event Handling Implementation

Let's check how event handlers and modifiers are written:

HTML — Vue Events
<!-- Simple event trigger shorthand -->
<button @click="incrementCount">Add Count</button>

<!-- Passing arguments to handlers -->
<button @click="deleteItem(item.id, $event)">Delete</button>

<!-- Form submission with prevent modifier -->
<form @submit.prevent="onFormSubmit">
  <!-- Trigger callback only on Enter key press -->
  <input @keyup.enter="submitSearch" placeholder="Type search term...">
  <button type="submit">Search</button>
</form>
3 Code Challenge
Challenge: Write a component template containing a box layout. Bind a mouse movement event (@mousemove) that displays the cursor's current X and Y coordinate parameters inside the box dynamically.