🎓 A1Learner
🔍
0 of 50 lessons completed

Form Modifiers

A form modifier is a small addition to v-model that changes how the input value is handled. Vue offers .lazy, .number, and .trim for common cases.

.lazy waits

The city ref updates when the person leaves the box.

<input v-model.lazy="city">

.number converts

The age ref holds a number, so it starts as 0.

<input v-model.number="age" type="number">

.trim cleans

Spaces at the ends of the typed name are removed.

<input v-model.trim="name">

Example

<script setup>
import { ref } from 'vue'
const name = ref('')
const city = ref('')
const age = ref(0)
</script>
<template>
  <div>
    <label>Name <input v-model.trim="name"></label>
    <label>City <input v-model.lazy="city"></label>
    <label>Age <input v-model.number="age" type="number"></label>
    <p>Name: {{ name }}</p>
    <p>City: {{ city }}</p>
    <p>Age: {{ age }} ({{ typeof age }})</p>
  </div>
</template>

Key points

  • A modifier is a word added after a dot that changes how a directive works.
  • .lazy updates the ref when the person leaves the box instead of on each keystroke.
  • .number turns the typed text into a number before it reaches the ref.
  • .trim removes spaces from the start and the end of the typed text.
  • Each modifier fits one job, so a form can mix them across its boxes.

In this example, name and city are refs that start as empty strings. age is a ref that starts as 0. The name box uses .trim, the city box uses .lazy, and the age box uses .number. Three paragraphs show the three answers. The age paragraph also shows the type of age, and it reads number. With Ada, Paris, and 25 typed in, the paragraphs show those three answers.

Note

.number needs a ref that holds a number, like 0.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which modifier turns typed text into a number?