Vue Forms 01 ๐ Native v-model Fundamentals โ Binding inputs, textareas, checkboxes, radio buttons, and select elements
Vueโs v-model directive provides a convenient syntax for implementing two-way bindings on form elements. It automatically picks the right event and property depending on the input type, keeping the UI and the underlying data model in sync. While the API appears simple, the underlying behavior differs across element types, and understanding those differences is key to building predictable forms. This chapter covers the fundamentals of v-model with every native HTML form element, explores the lazy, number, and trim modifiers, and provides a complete hands-on example session.
Intro prose
Form handling in Vue is centered around v-model. When applied to an <input>, textarea, or <select>, it listens for user input events and updates the bound data property immediately. On the flip side, whenever that data property changes, the elementโs value attribute is updated. This two-way connection works out of the box for text inputs, but each element typeโcheckbox, radio group, or selectโintroduces its own nuances. Additionally, v-model can be modified with .lazy, .number, and .trim to control exactly when and how the value is transformed. Mastering these patterns allows developers to build forms that are both user-friendly and easy to test, without resorting to manual event listeners or computed properties for simple bindings.
Key point
Key point: v-model automatically synchronizes the input elementโs value with a data property using the input event for most elements, but checkboxes and radio buttons use change, and select elements may emit change or input depending on the multiple attribute and programmatic updates; modifiers like .lazy, .number, and .trim alter the timing or type conversion of the bound value.
Why exists
The two-way binding problem. HTML forms inherently track their own state through DOM properties, while Vue apps thrive on a reactive data model. Before v-model, developers had to manually wire v-bind:value and @input (or `@change), which was verbose and error-prone across different element types.
Managing uncontrolled form state. In complex forms, keeping the Vue data object as the single source of truth while still allowing the browserโs native form validation and submission workflow required a unified abstraction that v-model provides out of the box.
Developer ergonomics. The Vue team designed v-model to reduce boilerplate and mental overhead, especially for beginners, by offering a single directive that works consistently across <input>, <textarea>, and <select> elements, with sensible defaults that can be customized via modifiers.
Cross-browser consistency. Different browsers may handle form serialization, default values, and event firing slightly differently. v-model normalizes these behaviors, ensuring that the Vue instance receives a predictable value regardless of the userโs browser.
Performance during frequent updates. Forms with many interactive elements can generate a high volume of events. v-modelโs internal logic ensures that only meaningful changes trigger re-renders, and modifiers like .lazy can batch updates to reduce unnecessary reactivity triggers.
Integration with validation libraries. Tools such as VeeValidate, Vuelidate, or FormKit build on top of v-model to inject error states, validation flags, and computed classes. Understanding the base v-model behavior is essential for extending or debugging these integrations.
a. Binding inputs and textareas
<input v-model="title" placeholder="Enter a title" />
<textarea v-model="body" rows="3"></textarea>
<script setup>
import { ref } from "vue";
const title = ref("");
const body = ref("");
</script>
For <input> and <textarea> elements, v-model binds the elementโs value property and listens for input events. As the user types, the input event fires with the current target value, and Vue updates the bound data property immediately. The same mechanism works in reverse: setting title or body in the component script automatically updates the elementโs displayed value. This default behavior is ideal for most text-entry scenarios, but it can be customized with modifiers when number parsing or whitespace trimming is required.
b. Checkboxes and radio buttons
<input type="checkbox" id="terms" v-model="accepted" />
<label for="terms">I accept the terms</label>
<input type="radio" name="color" id="red" value="red" v-model="color" />
<input type="radio" name="color" id="blue" value="blue" v-model="color" />
<label for="red">Red</label><label for="blue">Blue</label>
<script setup>
import { ref } from "vue";
const accepted = ref(false);
const color = ref(""); // initially empty, becomes "red" or "blue" when selected
</script>
Checkboxes and radio buttons differ from text inputs in two important ways. First, the true and false values are implicit: a checked checkbox sets the bound value to true, and an unchecked one sets it to false (or null if not initially bound). Second, these elements primarily fire the change event rather than input, meaning the bound model updates when the user finalizes their selection (e.g., clicks away or presses Enter), not on every keystroke or tick. This distinction is useful for performance but requires care when you need instant feedback. For three-state checkboxes (indeterminate), you can bind to null and use the :indeterminate attribute alongside v-model to visualize the middle state.
c. Select elements
<select v-model="selectedUser">
<option disabled value="">Select a user</option>
<option value="alice">Alice</option>
<option value="bob">Bob</option>
</select>
<script setup>
import { ref } from "vue";
const selectedUser = ref(""); // starts empty; updates on option selection
</script>
When v-model is used on a <select>, Vue binds the elementโs value and listens for change events emitted when the user chooses an option. The bound value becomes the value attribute of the selected <option>. For single-select lists, the initial value should match one of the option values or be empty if you want no pre-selection. The multiple attribute changes the behavior: v-model then expects an array, and the select element must have [] as the initial model. Each selected optionโs value is pushed into the array, and deselection removes it. Programmatic updates to the array are reflected instantly in the UI, and user interactions modify the array accordingly.
Complete Example Session
// ============================================
// PART 1: SETUP THE VUE COMPONENT
// ============================================
import { ref } from "vue";
const form = ref({
title: "",
body: "",
accepted: false,
color: "",
selectedUser: "",
});
// ============================================
// PART 2: INPUT AND TEXTAREA BINDINGS
// ============================================
// v-model on <input> and <textarea> updates the data property on every input event.
const title = form.value.title;
const body = form.value.body;
// ============================================
// PART 3: CHECKBOX BINDING
// ============================================
// A checked checkbox sets the model to true; unchecked sets it to false (or null if not initially bound).
const accepted = form.value.accepted;
// ============================================
// PART 4: RADIO BUTTON BINDING
// ============================================
// The model takes the value attribute of the selected radio button.
const color = form.value.color;
// ============================================
// PART 5: SELECT (SINGLE) BINDING
// ============================================
// The model becomes the value of the selected <option>.
const selectedUser = form.value.selectedUser;
// ============================================
// PART 6: MODIFIER .lazy
// ============================================
// With .lazy, the model updates on the change event instead of input, reducing reactivity overhead for text fields.
const lazyTitle = form.value.lazyTitle; // updates on blur/change, not keystroke
// ============================================
// PART 7: MODIFIER .number
// ============================================
// The .number modifier automatically converts the string input into a number, useful for quantity fields.
const quantity = form.value.quantity; // coerced to number if "42" is typed
// ============================================
// PART 8: MODIFIER .trim
// ============================================
// The .trim modifier strips leading and trailing whitespace from the input value.
const trimmedName = form.value.trimmedName; // " Alice " becomes "Alice"
// ============================================
// PART 9: COMPUTED DERIVED FROM v-model
// ============================================
// You can derive other values from the form state, such as an enable flag for a submit button.
const canSubmit = computed(() => form.value.accepted && form.value.title.trim().length > 0);
// ============================================
// PART 10: FORM SUBMISSION HANDLER
// ============================================
// On submit, prevent default and log or send the form data; the model is already in sync.
function handleSubmit(event) {
event.preventDefault();
console.log("Form data:", form.value);
}
The parts covered input and textarea bindings, checkbox and radio button behavior, select element handling, the .lazy, .number, and .trim modifiers, derived computed properties, and form submission using the pre-synchronized model.
Quick Reference
Native v-model Bindings
| Element | Event | Bound Value | Initial Value Note |
|---|---|---|---|
<input type="text"> | input | string | value prop or v-model default |
<textarea> | input | string | Same as input |
<input type="checkbox"> | change | true / false / null | Unchecked defaults to false |
<input type="radio"> | change | radio's value | Must have value attribute |
<select> (single) | change | option's value | First matching option selected |
<select multiple> | change | Array | value attributes of all selected options |
v-model Modifiers
| Modifier | Effect | Typical Use |
|---|---|---|
.lazy | Updates on change instead of input | Reduce reactivity on typing |
.number | Parses input to Number | Quantity, age, price fields |
.trim | removes leading/trailing whitespace | Name, address fields |
Best Practices
โ Do This:
// Use v-model without modifiers for simple two-way text binding
<input v-model="username" /> // โ
// Apply .number when expecting numeric input
<input v-model.number="age" /> // โ
// Apply .trim to clean user-entered strings
<input v-model.trim="name" /> // โ
// Group radio buttons with a common name and individual values
<input type="radio" value="A" v-model="choice" /> // โ
// Use :disabled bound to a derived property for form control
<button :disabled="!canSubmit">Submit</button> // โ
โ Don’t Do This:
// Omit v-model and manually bind value + emit input โ verbose and prone to mismatch
<input :value="name" @input="name = $event.target.value" /> // โ
// Apply .lazy to a field that needs real-time updates (e.g., live search)
<input v-model.lazy="query" /> // โ (use .trim or no modifier instead)
// Forget to provide an initial value for a select, leaving the model empty when an option is expected
<select v-model="opt"><option value="1">One</option></select> // โ set default or disabled option
// Bind v-model to a non-form element, expecting it to work like a two-way property
<div v-model="content">โฆ</div> // โ use @input/@output instead
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
Model stays null on checkbox | Checkbox initially unbound or checked attribute present | Bind v-model without checked, or set initial data to false |
Select always returns empty string | No option matches the initial model value, or multiple without array | Provide a disabled default option with matching value, or use v-model with array for multiple |
| Form doesnโt update when data changes programmatically | Using v-bind:value instead of v-model for the element | Replace :value + @input with v-model for consistency |
Unexpected true/false on radio group | Radio buttons not sharing the same name attribute, or values are strings vs. numbers | Ensure all radios in a group have identical name and coercionโsafe values |
input event fires too often, causing performance issues | Using v-model on large textareas without .lazy | Add .lazy or debounce the UI action that reads the model |
Real-World Examples
1. Basic contact form
<input v-model="form.name" placeholder="Name" />
<input v-model="form.email" type="email" placeholder="Email" />
<textarea v-model="form.message" rows="4"></textarea>
2. Acceptance checkbox with disabled submit
<input type="checkbox" id="terms" v-model="form.terms" />
<label for="terms">I agree to the terms</label>
<button :disabled="!form.terms">Submit</button>
3. Color selection with radio buttons
<input type="radio" name="theme" id="light" value="light" v-model="theme" />
<input type="radio" name="theme" id="dark" value="dark" v-model="theme" />
<p>Current theme: {{ theme }}</p>
4. User profile picture select
<select v-model="profile.pictureStyle">
<option value="default">Default</option>
<option value="rounded">Rounded</option>
<option value="circle">Circle</option>
</select>
5. Quantity input with .number
<input type="number" v-model.number="cart.quantity" min="1" />
<p>Qty: {{ cart.quantity }}</p>
6. Trimmed name input with .trim
<input v-model.trim="user.name" placeholder="Full name" />
<p>Hello, {{ user.name }}!</p>
7. Lazy-bound search input
<input v-model.lazy="searchQuery" @keyup.enter="performSearch" />
8. Form with validation schema
<form @submit.prevent="validate">
<input v-model="schema.title" required />
<button type="submit">Create</button>
</form>
9. Controlled component inside a modal
<modal v-model="isOpen">
<input v-model="modalForm.name" />
</modal>
10. Dynamic form generation
const fields = ref([
{ id: "name", label: "Name", type: "text", model: "form.name" },
{ id: "age", label: "Age", type: "number", model: "form.age" },
]);
Visual
The Two-Way Binding Flow (input element)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER TYPES "Alice" INTO INPUT โ
โ โโโถ v-model listens for 'input' event โ
โ โโโถ Vue updates data property: title โ "Alice" โ
โ โโโถ Vue re-renders input value: value="Alice"โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Two-Way Binding Flow (checkbox)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER CLICKS CHECKBOX โ
โ โโโถ v-model listens for 'change' event โ
โ โโโถ Vue toggles data property: accepted โ true/falseโ
โ โโโถ Input checked attribute updates accordinglyโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The .number and .trim Modifier Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER TYPES " 42 " INTO INPUT โ
โ โโโถ Without modifiers: model = " 42 " (string) โ
โ โโโถ With .number: model = 42 (number) โ
โ โโโถ With .trim: model = "42" (whitespace removed) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Select Element with v-model
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ USER SELECTS "Bob" FROM DROPDOWN โ
โ โโโถ <option value="Bob"> emits 'change' โ
โ โโโถ Vue sets model: selectedUser โ "Bob" โ
โ โโโถ <select> value attribute becomes "Bob" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Directive | v-model |
| Primary use | Two-way form bindings |
| Events used | input (text/textarea), change (checkbox/radio/select) |
| Modifiers | .lazy, .number, .trim |
| Select single | binds to option value, model is a string |
| Select multiple | binds to array, model updates on check/uncheck |
| Checkbox/radio | model is true/false/null or radio value |
Key takeaways:
v-modelis the standard Vue directive for synchronizing form inputs with component data, automatically mapping to the correct DOM event and property for each element type.- Text and textarea elements use the
inputevent, while checkboxes, radio buttons, and single selects usechange; this timing difference affects when the model updates during user interaction. - The
.numbermodifier coerces the input string into a numeric value,.trimstrips surrounding whitespace, and.lazydefers updates until thechangeevent, useful for performance-sensitive fields. - For
<select multiple>,v-modelexpects an array, and each selected optionโsvalueis added to or removed from that array. - Always provide a matching
valueattribute on radio buttons and<option>elements; otherwise the model may not bind as expected. - Use
v-modelfor consistency and reduced boilerplate, and replace manual:value+@inputpatterns withv-modelunless you need fine-grained event control.
Remember: Two-way binding in Vue forms is not magicโitโs a coordinated dance between the DOM elementโs value property, the appropriate event (input or change), and Vueโs reactivity system. Choose the right modifier for the job, respect the event differences across element types, and let v-model handle the synchronization so you can focus on application logic rather than DOM plumbing.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!