| | |

Vue Forms 02 ๐Ÿ“ v-model Modifiers & Custom Inputs โ€” Using .trim, .number, .lazy, and building reusable components with defineModel()

โฑ๏ธ Estimated read: 20 min | |

The first chapter of this series covered v-model on native elements. This chapter moves one level deeper: first into the three built-in modifiers that change when and how the bound value is produced, and then across the component boundary, where v-model on a custom component is a contract you define yourself rather than something the runtime hands you.

The two halves of the chapter are connected by a single idea. A modifier attached to a native element is applied by Vue’s own directive runtime โ€” you write .trim and the DOM value is trimmed before it reaches your ref. A modifier attached to a component, however, is only delivered โ€” Vue passes it into the child as a modelModifiers object and stops there. What the child does with it is entirely up to the component author.

That gap is exactly what defineModel(), stabilized in Vue 3.4, was designed to close. It collapses the old defineProps + defineEmits + computed bridge into one line, exposes the parent’s modifiers as a plain object, and gives the child a writable ref that both reads the parent’s value and emits the update. The sections that follow cover the three built-in modifiers and their fixed application order, the anatomy of a custom input built with defineModel(), named models for multi-value components, and the modifier-handling contract in full.

Key point: On a native element the modifiers .number, .trim, and .lazy are applied by Vue’s directive runtime in a fixed order (number before trim); on a component they are only delivered to the child as modelModifiers (or <name>Modifiers for named models), and the component must implement them itself.


Why exists

The boilerplate problem. Before Vue 3.4, a custom component that supported v-model needed four separate pieces: a modelValue prop declaration, an update:modelValue emit declaration, a computed with a getter reading the prop and a setter calling the emit, and a template binding to that computed. That is roughly six lines of ceremony for every input component, repeated identically each time. defineModel() compiles to exactly the same prop and emit pair but lets you write one line.

The silent type problem. HTML inputs never return numbers. Even with type="number", the DOM value property is a string, so a field bound to a ref(0) quietly becomes "0" the moment the user types. The .number modifier exists to close that gap with a parseFloat cast and a fallback to the original string when parsing fails, so a partially-typed "-" or "" does not become NaN.

The timing problem. By default v-model on a text input listens to the input event, which fires on every keystroke. For a search box that triggers a request, or a long textarea whose watchers are expensive, per-keystroke syncing is wasteful. The .lazy modifier swaps input for change, deferring the sync until the field loses focus or the form is submitted.

The whitespace problem. Users paste values with trailing spaces and leading newlines. Comparisons against "admin" fail against "admin ". The .trim modifier normalizes the value at the boundary, so no downstream code has to remember to call .trim() before comparing, validating, or storing.

The component boundary problem. A native element has an obvious place to apply a modifier: the DOM node itself. A custom component does not โ€” the parent’s v-model.trim refers to a value that passes through a prop, and the child may wrap any element beneath it. Vue resolves this by passing the modifiers object down as a prop and making the component responsible for honoring it. That decision is deliberate: it lets the component decide whether to apply the trim on input, on blur, or as part of a larger transformation.

The reusability problem. Every application accumulates the same handful of inputs โ€” a trimmed text field, a numeric field that ignores invalid characters, a currency field. Written once with v-model support and modifiers, each becomes a drop-in replacement with the same authoring experience as a native input; written without, each becomes a bespoke component with its own prop names and its own inconsistency.


a. The three built-in modifiers and their fixed order

Each modifier rewrites one specific step of the value pipeline. .number changes the type, .trim changes the content, and .lazy changes the event that starts the pipeline.

<script setup>
import { reactive } from "vue";

const product = reactive({
  price: 0,       // declared as a number, not a string
  sku: "",        // normalized text
  notes: "",      // long text, synced on blur
});
</script>

<template>
  <!-- .number: parseFloat the string; keep the raw string if parsing fails -->
  <input v-model.number="product.price" type="number" min="0" />

  <!-- .trim: strips leading and trailing whitespace on every update -->
  <input v-model.trim="product.sku" placeholder="SKU-001" />

  <!-- .lazy: sync on the change event (blur / Enter), not each keystroke -->
  <textarea v-model.lazy="product.notes" rows="3"></textarea>
</template>

.number internally calls a helper that runs parseFloat and checks the result with isNaN. If the parse succeeds the number is used; if it fails the original string is passed through unchanged. That fallback is why an empty field stays "" rather than becoming NaN, and why a lone minus sign while typing does not poison the model.

.trim calls String.prototype.trim on the raw DOM value before assigning it to the ref. .lazy does not touch the value at all โ€” it only changes which listener Vue attaches, swapping onInput for onChange.

The order in which the modifiers appear in the template does not matter. Vue reads them as an object and applies the number cast first, then the trim, regardless of how they were written.

<template>
  <!-- The runtime applies .number before .trim in both cases -->
  <input v-model.trim.number="quantityA" />
  <input v-model.number.trim="quantityB" />

  <!-- Input " 12 " produces the number 12 for both fields -->
</template>

This ordering is the sensible one. Trimming before casting would work for numeric strings but is not what the runtime does, and knowing the fixed order prevents surprises when a value like " 12abc " is cast to 12 and then trimmed (the trim has nothing left to remove). The practical rule is: never depend on the template order, and never rely on modifiers to validate โ€” .number coerces, it does not reject.


b. A custom input built with defineModel()

defineModel() is a compiler macro available in <script setup>. It declares a modelValue prop and an update:modelValue emit, and returns a writable ref whose value is sourced from and pushed to the parent.

<!-- BaseInput.vue -->
<script setup>
// One call replaces defineProps + defineEmits + computed.
// The returned ref is writable: reading gives the parent's value,
// writing emits update:modelValue.
const model = defineModel();
</script>

<template>
  <!-- Binding the ref to a native input delegates to v-model's DOM logic -->
  <input v-model="model" />
</template>

The parent consumes it with ordinary v-model syntax and sees no difference from a native input:

<!-- ParentForm.vue -->
<script setup>
import { ref } from "vue";
import BaseInput from "./BaseInput.vue";

const name = ref("");
</script>

<template>
  <!-- Compiles to :model-value="name" and @update:model-value="name = $event" -->
  <BaseInput v-model="name" />
  <p>Hello, {{ name }}</p>
</template>

Under the hood, defineModel() expands to something close to the pre-3.4 hand-written version, which is still valid and still worth recognizing when reading older code:

<script setup>
import { computed } from "vue";

// The manual equivalent of defineModel()
const props = defineProps({ modelValue: String });
const emit = defineEmits(["update:modelValue"]);

// A computed getter/setter bridges the incoming prop and the outgoing emit
const model = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});
</script>

The two forms are mutually exclusive inside one component: declare the model with defineModel() or with defineProps + defineEmits, never with both, because the compiler-generated prop would collide with the hand-written one.

One behavioral detail matters for real components. Because the returned ref is local state that syncs with the parent, a component that is used without a v-model binding still works โ€” the ref simply behaves as plain local state with nothing to emit to. That makes defineModel() usable as an optional two-way binding rather than a hard requirement.


c. Named models, multiple bindings, and typed declarations

A component can declare more than one model. Each defineModel() call takes an optional name, which becomes the prop name and the argument of the update event.

<!-- AddressFields.vue -->
<script setup>
// prop "street"  + event "update:street"
const street = defineModel("street");

// prop "city" + event "update:city", with prop options applied
const city = defineModel("city", { type: String, default: "" });
</script>

<template>
  <!-- Each ref is bound to its own input; edits on either emit upward -->
  <input v-model="street" placeholder="Street" />
  <input v-model="city" placeholder="City" />
</template>

The parent binds them with the argument form of v-model:

<script setup>
import { reactive } from "vue";
import AddressFields from "./AddressFields.vue";

const address = reactive({ street: "", city: "" });
</script>

<template>
  <!-- v-model:street maps to prop "street"; kebab-case also works -->
  <AddressFields v-model:street="address.street" v-model:city="address.city" />
</template>

Naming follows Vue’s standard prop convention. A template written as v-model:first-name targets the prop firstName, so the child declares defineModel("firstName"). Hyphenated attribute names and camelCase declarations are two spellings of the same prop.

The options object passed as the second argument is the prop declaration itself, so type, required, default, and validator all apply exactly as they would in defineProps:

<script setup>
// Enforces a typed, required model; a missing binding warns in development
const quantity = defineModel("quantity", {
  type: Number,
  required: true,
  validator: (value) => value >= 0,
});
</script>

Declaring the type is not cosmetic. It documents the contract, and Vue uses it for development-time warnings when a parent binds a string to a model declared as a number โ€” which happens constantly when .number is forgotten on a custom component.


d. Honoring modifiers inside a custom component

This is the part that separates a component that merely supports v-model from one that supports v-model.trim. When the parent writes a modifier, Vue collects them into a modelModifiers prop, and defineModel() exposes that object as the second element of the returned array.

<!-- TrimmedInput.vue -->
<script setup>
// modifiers is the parent's modifier object, e.g. { trim: true }
const [model, modifiers] = defineModel({
  // The setter runs on every write from the child template
  set(value) {
    // Apply the trim only when the parent asked for it
    return modifiers.trim ? value.trim() : value;
  },
});
</script>

<template>
  <!-- The inner binding feeds the setter; the setter shapes the emitted value -->
  <input v-model="model" />
</template>

Nothing is applied automatically. Without the set option above, the component would emit the raw string and the parent’s .trim would be silently ignored โ€” the modifier would travel all the way to the child and have no effect. This is the single most common mistake when building v-model components.

The same pattern covers the other two modifiers. A numeric input implements the cast itself:

<script setup>
const [model, modifiers] = defineModel({
  set(value) {
    // Mirror the runtime's behavior: cast when numeric, keep raw otherwise
    if (!modifiers.number) return value;
    const parsed = parseFloat(value);
    return Number.isNaN(parsed) ? value : parsed;
  },
});
</script>

And a lazy input switches which event it listens to, rather than which listener it attaches. Because v-model cannot take a dynamic event name, the component wires both handlers and gates each on the modifier:

<script setup>
const [model, modifiers] = defineModel();

// Only the handler that matches the requested sync mode is active
const onInput = (event) => {
  if (!modifiers.lazy) model.value = event.target.value;
};
const onChange = (event) => {
  if (modifiers.lazy) model.value = event.target.value;
};
</script>

<template>
  <!-- Both events are attached; the guards select the behavior -->
  <input :value="model" @input="onInput" @change="onChange" />
</template>

Named models get their own modifier object, named after the model: v-model:title.trim arrives as titleModifiers, and with defineModel("title") it is available as const [title, titleModifiers] = defineModel("title").

For cases where defineModel() cannot be used โ€” a composable that receives props as an argument, or a component that needs to read and write the model outside the <script setup> macro context โ€” Vue 3.4 also exports the useModel() composable.

// useModel works anywhere props are available, not just at the macro level
import { useModel } from "vue";

export function useNormalizedModel(props) {
  // The options mirror defineModel's: get and set can be customized
  return useModel(props, "modelValue", {
    set: (value) => String(value ?? "").trim(),
  });
}

Complete Example Session

<!-- ============================================ -->
<!-- PART 1: NATIVE MODIFIERS                     -->
<!-- ============================================ -->
<script setup>
import { reactive } from "vue";

const form = reactive({
  price: 0,
  sku: "",
  notes: "",
});
</script>

<template>
  <input v-model.number="form.price" type="number" min="0" />
  <input v-model.trim="form.sku" placeholder="SKU-001" />
  <textarea v-model.lazy="form.notes" rows="3"></textarea>
</template>

<!-- ============================================ -->
<!-- PART 2: FIXED APPLICATION ORDER              -->
<!-- ============================================ -->
<template>
  <!-- Both cast to a number, then trim; template order is irrelevant -->
  <input v-model.trim.number="form.price" />
  <input v-model.number.trim="form.price" />
</template>

<!-- ============================================ -->
<!-- PART 3: A MINIMAL CUSTOM INPUT               -->
<!-- ============================================ -->
<!-- BaseInput.vue -->
<script setup>
// Declares modelValue + update:modelValue and returns a writable ref
const model = defineModel();
</script>

<template>
  <input v-model="model" />
</template>

<!-- ============================================ -->
<!-- PART 4: THE PARENT USING IT                  -->
<!-- ============================================ -->
<!-- Parent.vue -->
<script setup>
import { ref } from "vue";
import BaseInput from "./BaseInput.vue";

const name = ref("");
</script>

<template>
  <BaseInput v-model="name" />
</template>

<!-- ============================================ -->
<!-- PART 5: HONORING .trim                       -->
<!-- ============================================ -->
<!-- TrimmedInput.vue -->
<script setup>
const [trimModel, trimModifiers] = defineModel({
  set(value) {
    // The parent's .trim only takes effect because of this line
    return trimModifiers.trim ? value.trim() : value;
  },
});
</script>

<template>
  <input v-model="trimModel" />
</template>

<!-- ============================================ -->
<!-- PART 6: HONORING .number                     -->
<!-- ============================================ -->
<!-- NumericInput.vue -->
<script setup>
const [numModel, numModifiers] = defineModel({
  set(value) {
    if (!numModifiers.number) return value;
    // parseFloat with an isNaN fallback, matching the runtime's behavior
    const parsed = parseFloat(value);
    return Number.isNaN(parsed) ? value : parsed;
  },
});
</script>

<template>
  <input v-model="numModel" inputmode="decimal" />
</template>

<!-- ============================================ -->
<!-- PART 7: HONORING .lazy                       -->
<!-- ============================================ -->
<!-- LazyInput.vue -->
<script setup>
const [lazyModel, lazyModifiers] = defineModel();

const onInput = (e) => {
  // Active only when the parent did NOT ask for lazy syncing
  if (!lazyModifiers.lazy) lazyModel.value = e.target.value;
};
const onChange = (e) => {
  // Active only when the parent asked for lazy syncing
  if (lazyModifiers.lazy) lazyModel.value = e.target.value;
};
</script>

<template>
  <input :value="lazyModel" @input="onInput" @change="onChange" />
</template>

<!-- ============================================ -->
<!-- PART 8: NAMED MODELS                         -->
<!-- ============================================ -->
<!-- AddressFields.vue -->
<script setup>
const street = defineModel("street");
const city = defineModel("city", { type: String, default: "" });
</script>

<template>
  <input v-model="street" placeholder="Street" />
  <input v-model="city" placeholder="City" />
</template>

<!-- Parent: v-model:street="address.street" v-model:city="address.city" -->

<!-- ============================================ -->
<!-- PART 9: TYPED MODEL WITH VALIDATOR           -->
<!-- ============================================ -->
<!-- QuantityPicker.vue -->
<script setup>
const quantity = defineModel("quantity", {
  type: Number,
  required: true,
  // Development warning when a negative number is bound
  validator: (value) => value >= 0,
});
</script>

<template>
  <input v-model.number="quantity" type="number" min="0" />
</template>

<!-- ============================================ -->
<!-- PART 10: useModel IN A COMPOSABLE            -->
<!-- ============================================ -->
<!-- useNormalizedModel.js -->
import { useModel } from "vue";

export function useNormalizedModel(props) {
  // Works outside the macro context; same get/set options as defineModel
  return useModel(props, "modelValue", {
    set: (value) => String(value ?? "").trim(),
  });
}

The ten parts covered the three native modifiers, the fixed number-then-trim ordering, a minimal defineModel() component, its parent, the three modifier-handling patterns (trim, number, lazy), named models with prop options, a typed model with a validator, and the useModel() composable for use outside the macro context.


Quick Reference

Native Modifiers

ModifierChangesImplementationReversible
.numberValue typeparseFloat + isNaN fallbackNo
.trimValue contentString.prototype.trimNo
.lazyTriggering eventchange instead of inputNo
CombinedType then contentNumber applied before trimNo

defineModel Forms

FormPropEvent
defineModel()modelValueupdate:modelValue
defineModel("title")titleupdate:title
defineModel({ type })modelValueupdate:modelValue
defineModel("n", { ... })nupdate:n

Modifier Delivery

Parent writesChild receivesAvailable as
v-model.trimmodelModifiersconst [m, mods] = defineModel()
v-model:title.trimtitleModifiersconst [t, mods] = defineModel("title")
No modifier{}Empty object
Multiple{ trim: true, number: true }Plain object

defineModel Options

OptionPurpose
typeDeclared prop type, drives dev warnings
defaultFallback when no binding
requiredWarns when the parent omits the binding
validatorFunction returning a boolean
getCustom read transform
setCustom write transform

Best Practices

โœ… Do This:

<!-- Use .trim on any text field compared downstream -->
<input v-model.trim="user.email" />                          <!-- โœ… -->

<!-- Use .number even with type="number"; the DOM returns strings -->
<input v-model.number="item.qty" type="number" />            <!-- โœ… -->

<!-- Use .lazy when a watcher is expensive or triggers a request -->
<input v-model.lazy="search.query" />                        <!-- โœ… -->

<!-- Declare the model type so mismatches warn in development -->
const qty = defineModel("qty", { type: Number });             <!-- โœ… -->

<!-- Implement modifiers explicitly in the child setter -->
set: (v) => modifiers.trim ? v.trim() : v                    <!-- โœ… -->

<!-- Prefer defineModel over the props/emit/computed trio -->
const model = defineModel();                                 <!-- โœ… -->

โŒ Don’t Do This:

<!-- Expecting the child to apply the modifier automatically -->
<MyInput v-model.trim="name" />  <!-- child ignores trim unless written -->  <!-- โŒ -->

<!-- Declaring the model twice in the same component -->
const model = defineModel();                                 <!-- โŒ -->
defineProps({ modelValue: String });                         // collision

<!-- Relying on .number to reject non-numeric input -->
<input v-model.number="age" />   <!-- coerces, does not validate -->  <!-- โŒ -->

<!-- Using .lazy where live feedback is required -->
<input v-model.lazy="preview" />  <!-- preview lags a blur behind -->  <!-- โŒ -->

<!-- Depending on the modifier order in the template -->
<input v-model.trim.number="x" />  // number runs first regardless  <!-- โŒ -->

Common Pitfalls

PitfallWhy It HappensFix
.trim on a component does nothingChild never implements modifiersAdd a set option reading modifiers.trim
Model becomes a string on a number field.number omitted; DOM returns stringsAdd .number or cast in the child
NaN appears in the modelManual casting without an isNaN guardMirror parseFloat + fallback
Prop/emit collision warningdefineModel() plus modelValue in definePropsUse one or the other
Named model never updatesv-model:first-name vs defineModel("firstname")Match the camelCase prop name
Search fires a request per keystrokeDefault input syncingAdd .lazy or debounce
Trim applied to a passwordOver-broad modifier on all text fieldsApply .trim only where whitespace is meaningless

Real-World Examples

1. Price field

<input v-model.number="cart.price" type="number" step="0.01" min="0" />

2. Normalized SKU

<input v-model.trim="product.sku" @blur="product.sku = product.sku.toUpperCase()" />

3. Notes synced on blur

<textarea v-model.lazy="order.notes" rows="4"></textarea>

4. Trimmed email component

<!-- EmailInput.vue -->
<script setup>
const [model, mods] = defineModel({ set: (v) => mods.trim ? v.trim() : v });
</script>

5. Numeric stepper

<!-- Stepper.vue -->
<script setup>
const quantity = defineModel("quantity", { type: Number, default: 1 });
</script>

6. Lazy search box

<input v-model.lazy="filters.q" @change="runSearch(filters.q)" />

7. Address with named models

<AddressFields v-model:street="a.street" v-model:city="a.city" />

8. Date range with two models

<DateRange v-model:from="range.from" v-model:to="range.to" />

9. Validation-aware quantity

const size = defineModel("size", { type: Number, validator: (v) => v > 0 });

10. Composable-wrapped model

export function useTrimmed(props) {
  return useModel(props, "modelValue", { set: (v) => v.trim() });
}

Visual

The Modifier Pipeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  DOM EVENT                                  โ”‚
โ”‚    input    (default)                       โ”‚
โ”‚    change   (.lazy)                         โ”‚
โ”‚        โ”‚                                    โ”‚
โ”‚        โ–ผ                                    โ”‚
โ”‚  FIXED ORDER OF APPLICATION                 โ”‚
โ”‚    1.  .number  โ†’  looseToNumber()          โ”‚
โ”‚    2.  .trim    โ†’  value.trim()             โ”‚
โ”‚        โ”‚                                    โ”‚
โ”‚        โ–ผ                                    โ”‚
โ”‚  BOUND REF                                  โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Native vs Component Modifier Handling

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  NATIVE ELEMENT                             โ”‚
โ”‚    v-model.trim  โ†’  Vue applies the trim    โ”‚
โ”‚                     before assigning        โ”‚
โ”‚                                             โ”‚
โ”‚  COMPONENT                                  โ”‚
โ”‚    v-model.trim  โ†’  Vue delivers            โ”‚
โ”‚                     modelModifiers          โ”‚
โ”‚                     The child decides       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The defineModel Compilation

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const model = defineModel()                โ”‚
โ”‚        โ”‚                                    โ”‚
โ”‚        โ”œโ”€โ”€โ–ถ  prop   modelValue              โ”‚
โ”‚        โ”œโ”€โ”€โ–ถ  emit   update:modelValue       โ”‚
โ”‚        โ””โ”€โ”€โ–ถ  prop   modelModifiers          โ”‚
โ”‚                                             โ”‚
โ”‚  read  model.value  โ†’  props.modelValue     โ”‚
โ”‚  write model.value  โ†’  emit(update:...)     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

The Four Patterns in a Child Component

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  set(v)   โ†’ shape the outgoing value        โ”‚
โ”‚             trim, cast, format              โ”‚
โ”‚                                             โ”‚
โ”‚  get()    โ†’ shape the incoming value        โ”‚
โ”‚             mask, prefix, transform         โ”‚
โ”‚                                             โ”‚
โ”‚  modifiers โ†’ read what the parent asked     โ”‚
โ”‚                                             โ”‚
โ”‚  events   โ†’ pick input vs change            โ”‚
โ”‚             for .lazy                       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Directivev-model with modifiers
Native modifiers.number, .trim, .lazy
Application orderNumber, then trim
.number internalsparseFloat with isNaN fallback
MacrodefineModel(), stable in Vue 3.4
Default propmodelValue / update:modelValue
Named modeldefineModel("title")
Modifier propmodelModifiers, or <name>Modifiers
Modifier handlingManual, inside the component
ComposableuseModel(props, key, options)

Key takeaways:

  • Native modifiers are applied; component modifiers are only delivered. Vue’s directive runtime handles v-model.trim on an <input> itself, but on a component it hands the modifiers object to the child and stops. A component that ignores modelModifiers silently ignores the modifier.
  • The runtime applies .number before .trim, regardless of template order. Writing v-model.trim.number and v-model.number.trim produces identical results, so never depend on the order modifiers were written.
  • .number coerces, it does not validate. It casts with parseFloat and falls back to the raw string when the cast fails, which keeps an in-progress "" or "-" from becoming NaN but lets "12abc" through as 12.
  • defineModel() replaces three declarations with one. It compiles to a modelValue prop, an update:modelValue emit, and a modelModifiers prop, and returns a writable ref that reads from the first and writes through the second.
  • Named models give a component several independent bindings. defineModel("street") pairs with v-model:street, with the attribute’s kebab-case converted to the camelCase prop name.
  • The set option is where modifier handling lives. It runs on every write from the child template, which makes it the natural place to trim, cast, or format before the value is emitted upward.
  • useModel() covers what the macro cannot. A composable that receives props as a plain argument cannot call defineModel(), but it can call useModel(props, "modelValue", { set }) and get the same behavior.

Remember: A v-model modifier is a message from parent to child, not an instruction the framework executes on the child’s behalf. On a native element Vue reads that message and acts on it immediately; on a component it is forwarded through modelModifiers and the component decides. That is why a component can support v-model perfectly and still ignore v-model.trim โ€” the two are separate promises. defineModel() makes both promises cheap to keep: one line declares the contract, and a set option implements the modifiers the parent may attach.

Was this helpful?


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!