Learn Vue.js · 4/13

Interactivity: Event Handling and Forms

7 min read

Imagine you are designing the touchscreen ordering system for a wildly busy, understaffed coffee shop. The screen displays all the beautiful menu items, but right now, it is just a digital painting. When a customer frantically taps the "Double Espresso" button, nothing happens. When they try to type their name for the order, the screen ignores them.

A user interface without interactivity is just a poster. In modern web development, your application needs to respond to clicks, keystrokes, form submissions, and occasionally, the frustrated key-mashing of your users.

In this guide, we are going to explore how Vue.js handles user interactions and forms. We will use the modern Vue 3 Composition API (<script setup>) because that is what you will encounter in professional industry codebases today.


1. Listening to DOM Events with v-on

The Problem

Browsers naturally detect when a user clicks a button, scrolls a page, or presses a key. However, by default, your JavaScript logic is completely unaware of these actions. You need a way to tell your application, "When the user clicks this specific button, run this specific function."

The Solution: v-on

v-on is a Vue directive used to attach event listeners to DOM elements. It listens for native DOM events (like click, keyup, mouseenter) and executes JavaScript when those events occur.

Under the hood, Vue is simply calling the standard browser addEventListener() API when the component mounts, and—crucially—it automatically calls removeEventListener() when the component is destroyed. This saves you from the notorious memory leaks that plagued early JavaScript applications.

Industry Standard Usage

In the industry, you will almost never see v-on:click. Instead, developers use the shorthand @.

vue
<script setup>
import { ref } from 'vue'

const orderCount = ref(0)

// Method handler
const placeOrder = () => {
  orderCount.value++
  console.log(`Order placed! Total orders: ${orderCount.value}`)
}

// Method handler with an argument
const orderSpecificCoffee = (coffeeType) => {
  console.log(`One ${coffeeType} coming right up!`)
}
</script>

<template>
  <div class="coffee-pos">
    <!-- Inline handler (good for tiny operations) -->
    <button @click="orderCount++">Quick Add Order</button>

    <!-- Method handler (the standard for business logic) -->
    <button @click="placeOrder">Place Standard Order</button>

    <!-- Passing arguments -->
    <button @click="orderSpecificCoffee('Latte')">Order Latte</button>
  </div>
</template>

Accessing the Event Object

Sometimes you need to know exactly what triggered the event—like finding the exact X and Y coordinates of a click. If you don't pass any arguments to your function, Vue automatically passes the native DOM event object. If you need to pass an argument and the event object, you can use the special $event variable.

vue
<script setup>
const handleComplexClick = (message, event) => {
  console.log(message)
  console.log('User clicked at:', event.clientX, event.clientY)
}
</script>

<template>
  <button @click="handleComplexClick('Hello World', $event)">
    Click for Coordinates
  </button>
</template>

2. Using Event Modifiers for Cleaner Code

The Problem

Look at this standard vanilla JavaScript form submission:

javascript
function handleSubmit(event) {
  event.preventDefault(); // Stop the page from reloading
  event.stopPropagation(); // Stop the event from bubbling up the DOM
  // ... actual business logic starts here
}

Mixing DOM manipulation (preventDefault) with business logic (handling the data) violates the principle of separation of concerns. You want your functions to deal solely with data, not with fighting the browser's default behaviors.

The Solution: Event Modifiers

Event modifiers are postfixes added to the v-on (@) directive that tell Vue to handle DOM event details automatically.

By adding .prevent to your @submit listener, Vue calls event.preventDefault() for you before your function even runs.

Frequently Used Modifiers in Industry

You do not need to memorize all of them, but these are the ones you will use daily:

  • .prevent: Prevents the default browser action (crucial for forms).
  • .stop: Stops event bubbling (prevents parent elements from also firing click events).
  • .once: Fires the event listener exactly one time.
vue
<script setup>
const processPayment = () => {
  // We don't need to write event.preventDefault() here!
  // We just focus on taking the customer's money.
  console.log("Processing payment...")
}
</script>

<template>
  <!-- Chaining modifiers: Stops bubbling AND prevents page reload -->
  <form @submit.prevent.stop="processPayment">
    <button type="submit">Pay Now</button>
  </form>

  <!-- Only allows the user to click the discount button once -->
  <button @click.once="applyDiscount">Apply 10% Discount</button>
</template>

Fun Fact: You can chain modifiers together, like @click.stop.prevent. However, order matters! @click.prevent.self will prevent all clicks, while @click.self.prevent will only prevent clicks on the element itself.


3. Two-Way Data Binding with v-model

The Problem

In an interactive application, you frequently need to sync what the user types in an <input> field with a JavaScript variable.
To do this manually, you have to:

  1. Bind the input's value attribute to your variable.
  2. Listen to the input's @input event.
  3. Update the variable with event.target.value.
vue
<!-- The hard way (Don't do this) -->
<input 
  :value="customerName" 
  @input="event => customerName = event.target.value" 
/>

Doing this for a form with 15 fields will make you question your career choices.

The Solution: v-model

v-model is a directive that creates a two-way data binding on form inputs, textareas, and select elements. It automatically syncs the input's value with your JavaScript state.

Under the hood, v-model is literally just syntactic sugar for the "hard way" shown above. It binds the value and listens to the input event simultaneously.

vue
<script setup>
import { ref } from 'vue'

const customerName = ref('')
const specialInstructions = ref('')
</script>

<template>
  <div>
    <label>Customer Name:</label>
    <!-- As the user types, customerName updates instantly -->
    <!-- If customerName is updated via JS, the input field updates instantly -->
    <input v-model="customerName" type="text" />
    
    <label>Instructions:</label>
    <textarea v-model="specialInstructions"></textarea>

    <p>Current Order for: {{ customerName }}</p>
  </div>
</template>

4. Form Input Modifiers and Handling Multiple Input Types

The Problem

Users are brilliantly unpredictable. If you ask for their age, they might type it with trailing spaces (" 25 "). If you ask for a number, the HTML DOM natively returns it as a string ("25" instead of 25), which can accidentally turn 25 + 1 into "251" in your code.

The Solution: Form Modifiers

Just like event modifiers, v-model has its own set of modifiers to clean up user input before it hits your state.

Industry Standard Modifiers

  1. .trim: Automatically strips leading and trailing whitespace. (Always use this for usernames, emails, and passwords).
  2. .number: Automatically typecasts the input to a JavaScript Number. If the value cannot be parsed, it returns the original string.
  3. .lazy: By default, v-model syncs on every single keystroke (input event). .lazy changes this to sync only when the user clicks away from the input (change event). Great for heavy search queries.
vue
<script setup>
import { ref } from 'vue'

const email = ref('')
const age = ref(null)
const searchKey = ref('')
</script>

<template>
  <!-- Removes accidental spaces -->
  <input v-model.trim="email" type="email" placeholder="Email" />

  <!-- Ensures 'age' is a Number type, not a String -->
  <input v-model.number="age" type="number" placeholder="Age" />

  <!-- Won't update 'searchKey' until the user clicks outside the box -->
  <input v-model.lazy="searchKey" type="text" placeholder="Search..." />
</template>

Handling Multiple Input Types (Checkboxes, Radios, Selects)

v-model is smart enough to adapt its behavior based on the HTML input type. You don't need to figure out if you should look at the checked property or the value property; Vue does the heavy lifting.

vue
<script setup>
import { ref } from 'vue'

// Booleans for single checkboxes
const wantsReceipt = ref(false)

// Arrays for multiple checkboxes
const selectedToppings = ref([])

// Strings for radio buttons and dropdowns
const coffeeSize = ref('Medium')
const paymentMethod = ref('')
</script>

<template>
  <form @submit.prevent>
    
    <!-- Single Checkbox: Binds to a boolean -->
    <label>
      <input type="checkbox" v-model="wantsReceipt" /> 
      Email Receipt?
    </label>

    <hr/>

    <!-- Multiple Checkboxes: Binds to an Array -->
    <h4>Add Toppings:</h4>
    <label><input type="checkbox" v-model="selectedToppings" value="Vanilla"> Vanilla</label>
    <label><input type="checkbox" v-model="selectedToppings" value="Caramel"> Caramel</label>
    <p>Toppings chosen: {{ selectedToppings }}</p> <!-- Outputs: ['Vanilla'] -->

    <hr/>

    <!-- Radio Buttons: Binds to a single String -->
    <h4>Size:</h4>
    <label><input type="radio" v-model="coffeeSize" value="Small"> Small</label>
    <label><input type="radio" v-model="coffeeSize" value="Medium"> Medium</label>
    <label><input type="radio" v-model="coffeeSize" value="Large"> Large</label>

    <hr/>

    <!-- Select Dropdown: Binds to a single String -->
    <h4>Payment Method:</h4>
    <select v-model="paymentMethod">
      <option disabled value="">Please select one</option>
      <option value="credit">Credit Card</option>
      <option value="cash">Cash</option>
      <option value="app">Mobile App</option>
    </select>

  </form>
</template>

By mastering @ for actions and v-model for data entry, you effectively build the bridge between the static DOM and your dynamic JavaScript logic.


References & Extra Reading

To deepen your understanding, check out the official Vue 3 documentation. Always refer to the official docs for the most up-to-date APIs and edge cases.

Challenge

Vue.js Advanced Form Handling Challenge

You are tasked with building a user registration form using Vue 3's Composition API. You must correctly apply event handlers and data binding directives with their respective modifiers to create a fully functional and robust form.

Requirements:

  1. Data Binding (v-model):

    • Bind the username input to the formData.username ref. Ensure any leading/trailing whitespace is automatically removed.
    • Bind the age input to the formData.age ref. This binding should only update the data when the input loses focus (on the change event), and it should attempt to convert the input value to a JavaScript Number.
    • Bind the single "I agree to the terms" checkbox to the formData.agreedToTerms boolean ref.
    • Bind the multiple "Interests" checkboxes to the formData.interests array ref. Checking/unchecking these boxes should add/remove the corresponding value from the array.
    • Bind the <select> dropdown to the formData.selectedCountry ref.
  2. Event Handling (v-on or @):

    • Attach an event handler to the <form> element that calls the submitForm method upon submission. This handler must prevent the default browser behavior of a page reload.
    • Attach a click event handler to the "Register Once" button that also calls the submitForm method. This button must be configured to only trigger its event handler a single time.
    • Attach a click event handler to the "Reset" button that calls the resetForm method. You must ensure that this click event does not propagate up the DOM tree (event bubbling is stopped).

Expected result

Your final code should correctly implement a Vue 3 component with a form that demonstrates the following behaviors:

  • Username Input: Is two-way bound to formData.username. Any whitespace entered at the beginning or end of the input is automatically stripped from the underlying data model due to the .trim modifier.
  • Age Input: Is two-way bound to formData.age. The formData.age ref only updates after the user clicks away from the input field (on blur) because of the .lazy modifier. The value is automatically type-casted to a number via the .number modifier.
  • Terms Checkbox: Is two-way bound to the formData.agreedToTerms boolean. Toggling the checkbox changes the value between true and false.
  • Interests Checkboxes: Are all two-way bound to the formData.interests array. When a box is checked, its value is pushed to the array. When unchecked, its value is removed.
  • Country Select: Is two-way bound to formData.selectedCountry. The data reflects the value of the currently selected <option>.
  • Form Submission: Submitting the form by clicking the "Submit Form" button triggers the submitForm method without reloading the page, due to the @submit.prevent directive on the <form> tag.
  • Register Once Button: Clicking this button calls submitForm, but subsequent clicks do nothing because of the @click.once modifier.
  • Reset Button: Clicking this button calls the resetForm method. The event's propagation is stopped by the @click.stop modifier.
html

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.