0
0
VueHow-ToBeginner · 3 min read

How to Use v-model Modifiers in Vue for Better Input Handling

In Vue, v-model modifiers like .lazy, .number, and .trim change how data binding works by controlling when and how input values update. Use them by adding the modifier after v-model, for example, v-model.lazy updates the model only on change events instead of input events.
📐

Syntax

The v-model directive binds input elements to data. Modifiers adjust this binding behavior:

  • .lazy: Updates the model on change event instead of input.
  • .number: Converts input string to a number automatically.
  • .trim: Removes whitespace from input before updating the model.

Use them by appending after v-model, like v-model.lazy.

vue
<input v-model.lazy="message" />
<input v-model.number="age" />
<input v-model.trim="username" />
💻

Example

This example shows three inputs using v-model modifiers: .lazy updates only on blur, .number converts input to number, and .trim removes spaces.

vue
<template>
  <div>
    <label>Lazy Input (updates on blur):</label>
    <input v-model.lazy="lazyText" />
    <p>Value: {{ lazyText }}</p>

    <label>Number Input (auto converts):</label>
    <input v-model.number="age" type="number" />
    <p>Value (type: {{ typeof age }}): {{ age }}</p>

    <label>Trim Input (removes spaces):</label>
    <input v-model.trim="username" />
    <p>Value: '{{ username }}'</p>
  </div>
</template>

<script setup>
import { ref } from 'vue'
const lazyText = ref('')
const age = ref(null)
const username = ref('')
</script>
Output
Three input fields: 1) Lazy input updates value only after you leave the field. 2) Number input converts typed text to a number type. 3) Trim input removes spaces before and after text.
⚠️

Common Pitfalls

Common mistakes when using v-model modifiers include:

  • Using .number on non-numeric inputs causes NaN.
  • Expecting .lazy to update on every keystroke (it updates only on change/blur).
  • Forgetting .trim only removes spaces at start/end, not inside the string.

Always choose modifiers based on input type and desired update timing.

vue
<!-- Wrong: number modifier on text input -->
<input v-model.number="textValue" />

<!-- Right: number modifier on numeric input -->
<input v-model.number="age" type="number" />
📊

Quick Reference

ModifierEffectWhen to Use
.lazyUpdates model on change event (blur)When you want fewer updates, e.g., on blur
.numberConverts input string to numberFor numeric inputs to keep data type correct
.trimTrims whitespace from inputTo avoid accidental spaces in text inputs

Key Takeaways

Use .lazy to update model only on change events like blur.
Use .number to automatically convert input strings to numbers.
Use .trim to remove leading and trailing spaces from input.
Choose modifiers based on input type and desired update timing.
Avoid .number on non-numeric inputs to prevent NaN values.