Form Input Bindings (v-model & Modifiers)

💚 Vue.js Lesson 9 Intermediate

The v-model directive simplifies form handling by establishing two-way data binding between inputs and component state, automatically syncing values on user changes.

1 v-model input types and modifiers

Vue's form bindings handle diverse input elements out of the box:

  • Input controls: Auto-syncs texts inputs, select dropdown lists, checkboxes, and radio buttons.
  • .lazy Modifier: Syncs values after change events instead of input events (e.g. when focus leaves the input).
  • .number Modifier: Automatically casts user inputs to JavaScript numbers.
  • .trim Modifier: Automatically trims leading and trailing whitespace from inputs.
2 Form Inputs Bindings Layout

Let's check form bindings in a template:

HTML — Form Bindings
<form @submit.prevent="saveForm">
  <!-- Trimmed input -->
  <input v-model.trim="user.name" placeholder="Name">

  <!-- Number input -->
  <input v-model.number="user.age" type="number" placeholder="Age">

  <!-- Dropdown select -->
  <select v-model="user.country">
    <option value="us">United States</option>
    <option value="in">India</option>
  </select>

  <!-- Single Checkbox (Boolean) -->
  <label>
    <input type="checkbox" v-model="user.subscribe"> Subscribe to newsletters
  </label>

  <button type="submit">Submit</button>
</form>
3 Code Challenge
Challenge: Write a form template containing checkboxes bound to a single reactive array called selectedSkills. Validate that at least two skills are selected before allowing form submission.