In the previous lesson you saw that, for a child to modify a piece of the parent's data, a pair is needed: a prop that passes the value down and an event with which the child asks for it to be changed. That is exactly what form controls and filters need: the parent owns the data, but it is the child that edits it. Writing that pair by hand for every field is repetitive, so on components Vue offers the same shortcut you already use on <input>s: v-model. In this lesson you will see what v-model turns into when you put it on a component, how to implement it with the defineModel() macro (Vue 3.4+), how to use several v-models on the same component, how to create your own modifiers and what the manual implementation looked like, which you will find in a lot of existing code. With all this we will create TextField, RoomFilters and, at last, BookingForm, which will relieve App.vue of its two biggest blocks.
Contents
- What
v-modeldoes on a component defineModel(): the modern waydefineModeloptions:required,defaultandtype- Several
v-models with arguments - Modifiers: built-in and custom
- The manual implementation (before Vue 3.4)
- The classic mistake: mutating a model object
- Case study:
TextField,RoomFiltersandBookingForm
- What
v-model does on a component
v-model does on a componentIn Data Binding you discovered that, on an <input>, v-model is syntactic sugar for :value plus the input event. On a component, v-model expands to another pair, always the same one:
<!-- What you write -->
<TextField v-model="form.member" />
<!-- What the compiler generates -->
<TextField
:model-value="form.member"
@update:model-value="(value) => (form.member = value)"
/>- A prop called
modelValue, with the current value. - An event called
update:modelValue, with which the child communicates the new value. The parent listens to it and assigns it.
This is exactly the prop + event pattern from the previous lesson, with fixed names. The flow is still one-way: the child never modifies the prop; it emits the new value, the parent updates its data and the updated prop comes down.
sequenceDiagram
participant U as User
participant T as TextField
participant F as Parent (form)
F->>T: prop modelValue = 'Laur'
U->>T: types "a"
T->>F: emit('update:modelValue', 'Laura')
F->>F: form.member = 'Laura'
F->>T: prop modelValue = 'Laura'
What the child component has to do, therefore, is declare the modelValue prop and the update:modelValue event, and connect them to its internal control. There is a modern way and a manual way of doing this.
defineModel(): the modern way
defineModel(): the modern waySince Vue 3.4, the defineModel() macro does all the work:
<!-- A minimal field -->
<script setup>
const model = defineModel()
</script>
<template>
<input v-model="model" />
</template>defineModel() returns a special ref:
- When you read it (
model.value, ormodelin the template), it returns the value of themodelValueprop. - When you assign it (
model.value = 'x'), it emitsupdate:modelValuewith the new value. It does not modify the prop: it asks the parent to do so.
That is why, in the template, you can use an ordinary v-model on the inner <input>: the input reads the ref and, when the user types, assigns it, which emits the event towards the parent. Two chained v-models connect the parent's data with the child's <input>.
Under the hood, the macro declares the modelValue prop, the modelModifiers prop (section 5) and the update:modelValue event for you. In Vue DevTools you will see those props on the component.
A useful detail: if the parent does not use v-model on the component, the ref works like ordinary local state. The component keeps working on its own; it is just that nobody outside finds out about the changes.
defineModel options: required, default and type
defineModel options: required, default and typedefineModel accepts the same options as a prop:
// Required: warns if the parent does not use v-model
const model = defineModel({ required: true })
// With a type and a default value
const sort = defineModel('sort', { type: String, default: 'none' })
// Several accepted types
const value = defineModel({ type: [String, Number] })| Option | Effect | When to use it |
|---|---|---|
type |
Checks the value's type in development, as with a prop | Whenever the type is known |
required: true |
Warns if the parent does not bind the model | When the component makes no sense without it |
default |
The value the ref takes if the parent passes none | Components that can work without v-model |
get / set |
Transform the value when it is read or before it is emitted | Custom modifiers (section 5) |
Be careful with default. If the parent uses the component without v-model, or binds a variable whose value is undefined, the child will show the default value but the parent will still have undefined: child and parent are out of sync until the first change. The safe approach is for the parent always to initialise its data with the same value as the child's default, or not to use default when the model is required.
- Several
v-models with arguments
v-models with argumentsA component can have several models. Each one is distinguished by an argument after the colon:
<!-- Parent -->
<RoomFilters
v-model:floor="floorFilter"
v-model:min-capacity="minCapacity"
v-model:sort="sort"
/>With an argument, the pair changes its name: v-model:floor uses the floor prop and the update:floor event. In the child, the name is passed as the first parameter of defineModel:
// RoomFilters.vue
const floor = defineModel('floor', { type: Number, default: null })
const minCapacity = defineModel('minCapacity', { type: Number, default: 1 })
const sort = defineModel('sort', { type: String, default: 'none' })The same naming rules apply as with props: in the script the name is written in camelCase (minCapacity) and in the parent's template in kebab-case (v-model:min-capacity). Vue does the conversion.
A v-model without an argument is equivalent to v-model:modelValue. You can combine one without an argument with several that have one although, when a component has several models of equal importance, such as the filters, it is clearer for all of them to have names.
Why not a single v-model="filters" with an object? It is tempting, but it leads to the mistake we will see in section 7. Several models with simple values are clearer, and each one is updated separately.
- Modifiers: built-in and custom
5.1 .trim and .number work on their own
The modifiers you know from Forms with v-model also work on components:
<TextField v-model.trim="form.member" label="Name" />
<TextField v-model.number="form.attendees" label="Attendees" />Vue applies them automatically: when the child emits an update:... event, Vue checks whether the parent used .trim or .number on that model and transforms the value before handing it over. The component does not have to do anything. .lazy, on the other hand, depends on which DOM event the internal control uses, so it has no automatic effect on a component.
5.2 Custom modifiers
You can invent your own modifiers. Vue passes the child an object with the ones the parent has used, and defineModel returns it as the second element if you destructure the result as an array:
// Child
const [model, modifiers] = defineModel({
set(value) {
// Runs before emitting: whatever it returns is what the parent receives
if (modifiers.uppercase && typeof value === 'string') {
return value.toUpperCase()
}
return value
}
})
console.log(modifiers) // { uppercase: true }modifiersis an object with atruekey for each modifier used. If the parent uses none, it is empty.set(value)intercepts every assignment to the ref: the value you return is the one that is emitted. It is the natural place to transform.get(value)is the reverse operation: it transforms the prop's value when it is read (for example, to display it in another format).
With a model that has an argument, the syntax is the same: v-model:search.uppercase="..." and, in the child, const [search, modifiers] = defineModel('search', { set... }).
- The manual implementation (before Vue 3.4)
defineModel is relatively recent, and you will find a great deal of code that implements v-model by hand. It is the same pair as in the previous lesson, with fixed names:
<!-- TextField implemented by hand -->
<script setup>
const { modelValue = '' } = defineProps({ modelValue: String })
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>Notice that the inner <input> cannot use v-model="modelValue": it would be trying to assign a prop. That is why it is split into :value and @input. If you prefer to use v-model inside, the classic pattern is a writable computed property, which you already know from Computed Properties and Watchers:
const props = defineProps({ modelValue: String })
const emit = defineEmits(['update:modelValue'])
const model = computed({
get: () => props.modelValue,
set: (value) => emit('update:modelValue', value)
})
// In the template: <input v-model="model" />This is, in essence, what defineModel does for you. Custom modifiers arrived as one more prop, modelModifiers (or floorModifiers for v-model:floor), which had to be declared with default: () => ({}).
And if the code uses the Options API, or dates from the Vue 2 era, you will see these variants:
| Era / style | Prop | Event | Several models |
|---|---|---|---|
Vue 3 + defineModel (3.4+) |
Declared by the macro | Emitted when the ref is assigned | defineModel('floor') |
| Vue 3 manual / Options API | modelValue |
update:modelValue (this.$emit(...) in Options) |
v-model:floor → floor prop, update:floor event |
| Vue 2 | value |
input (configurable with the model option) |
.sync modifier: :floor.sync="x" listened to update:floor |
If you are migrating Vue 2 code, remember that .sync disappeared in Vue 3: v-model:floor replaces it.
- The classic mistake: mutating a model object
Imagine that, instead of several models, RoomFilters receives all the filters in one object:
<!-- Parent -->
<RoomFilters v-model="filters" />
<!-- with: const filters = ref({ floor: null, minCapacity: 1, sort: 'none' }) -->// Child — ❌ incorrect
const filters = defineModel()
function chooseFloor(floor) {
filters.value.floor = floor // mutates the parent's object directly
}It appears to work: the parent sees the change. But what actually happens is that the child modifies a property of the parent's object without going through the event: filters.value.floor = ... reads the ref (getting the object) and modifies that object; it never assigns the ref, so update:modelValue is not emitted. It is the object trap you saw in 03-02, in a different disguise. The consequences:
- If the parent needs to react to the event (for example, to save the filters or validate them), it never finds out.
- If the parent passes a read-only (
readonly) or computed object, the mutation fails or is lost. - Anyone reading the parent's code has no way of knowing that the child modifies its object.
The correct way is to assign a new object, which does emit the event:
And the best solution, when the fields are independent, is not to use an object at all: several v-models with arguments, each with a simple value, as we will do with RoomFilters.
- Case study:
TextField, RoomFilters and BookingForm
TextField, RoomFilters and BookingForm8.1 TextField.vue: a field with a label and an error
The booking form repeats the same pattern for every field: a <label> linked by id, the control, the aria-invalid and aria-describedby attributes and an error paragraph. It is the perfect candidate for a generic component. Create src/components/base/TextField.vue:
<script setup>
import { useId } from 'vue'
// The value: the parent's v-model (accepts the custom .uppercase modifier)
const [model, modifiers] = defineModel({
type: [String, Number],
set(value) {
if (modifiers.uppercase && typeof value === 'string') {
return value.toUpperCase()
}
return value
}
})
const { label, error = '', inputType = 'text' } = defineProps({
label: { type: String, required: true },
error: String, // error message already decided by the parent ('' = no error)
inputType: String // temporary: in 03-05 the fallthrough type attribute will replace it
})
// Temporary: in 03-05 the parent's @blur will reach the <input> without being declared
const emit = defineEmits(['blur'])
// Unique identifier per instance: links the label, the input and the error message
const id = useId()
const errorId = `${id}-error`
</script>
<template>
<div class="field">
<label :for="id">{{ label }}</label>
<input
:id
v-model="model"
:type="inputType"
:aria-invalid="error ? 'true' : 'false'"
:aria-describedby="error ? errorId : null"
@blur="emit('blur')"
/>
<p v-if="error" :id="errorId" class="error">{{ error }}</p>
</div>
</template>
<style scoped>
.field {
display: grid;
gap: 0.3rem;
}
input {
padding: 0.5rem;
border: 1px solid #bbbbbb;
border-radius: 6px;
font: inherit;
}
input[aria-invalid='true'] {
border-color: #c62828;
}
.error {
margin: 0;
color: #c62828;
font-size: 0.9rem;
}
</style>Let's go over the pieces:
defineModelwithtype: [String, Number]: the same component works for text, dates (strings such as'2026-11-03') and numbers (withv-model.number). Thesetfunction implements the.uppercasemodifier.useId()(Vue 3.5) generates a unique, stable identifier for each instance. It is the solution to the problem of repeatedids that we pointed out in 03-01: with tenTextFields on the page, each one will have its own, and the<label for>and thearia-describedbywill always point to the right element. (:idis shorthand for:id="id".)errorarrives already decided by the parent.TextFielddoes not know how to validate: it only knows how to display an error. The validation logic stays in the form, which is the one that knows the rules.inputTypeand theblurevent are temporary. If the parent wrotetype="date"or@blurdirectly on<TextField>, today they would end up on the root<div>, not on the<input>. In Template Refs and Fallthrough Attributes we will learn how to redirect them and we will remove these two patches.<style scoped>: the field brings its own styles; it no longer depends on the parent defining.fieldor.error.
8.2 RoomFilters.vue: several v-models
The catalogue filters (floor, minimum capacity, equipment and sort order) and the search box are controls that the user edits but whose values App needs in order to calculate visibleRooms. It is the textbook case for several v-models. Create src/components/RoomFilters.vue:
<script setup>
import { ref, watch } from 'vue'
// --- Models: the owners of this data are in the parent ---
const floor = defineModel('floor', { type: Number, default: null }) // null = all
const minCapacity = defineModel('minCapacity', { type: Number, default: 1 })
const equipment = defineModel('equipment', { type: String, default: '' }) // '' = any
const sort = defineModel('sort', { type: String, default: 'none' })
const search = defineModel('search', { type: String, default: '' })
// --- Input data: read-only ---
const { equipmentOptions = [] } = defineProps({ equipmentOptions: Array })
// --- Presentation options (they move here from App.vue) ---
const capacityOptions = [1, 4, 8, 12]
const sortOptions = [
{ value: 'none', label: 'Unsorted' },
{ value: 'price-asc', label: 'Cheapest first' },
{ value: 'price-desc', label: 'Most expensive first' }
]
function toggleEquipment(item) {
equipment.value = equipment.value === item ? '' : item
}
// --- Search box: the text is edited locally and applied with Enter ---
const searchText = ref(search.value)
// If the parent clears the search (e.g. with "Clear filters"), the field is emptied too
watch(search, (value) => {
searchText.value = value
})
function applySearch() {
search.value = searchText.value // assigning the model emits update:search
}
function clearSearch() {
searchText.value = ''
search.value = ''
}
</script>
<template>
<div class="filters">
<p>
Floor:
<button class="button" :class="{ 'button--active': floor === null }" @click="floor = null">
All
</button>
<button
v-for="number in 3"
:key="number"
class="button"
:class="{ 'button--active': floor === number }"
@click="floor = number"
>
{{ number }}
</button>
</p>
<p>
Minimum capacity:
<button
v-for="min in capacityOptions"
:key="min"
class="button"
:class="{ 'button--active': minCapacity === min }"
@click="minCapacity = min"
>
{{ min }}+
</button>
</p>
<p>
Equipment:
<button
v-for="item in equipmentOptions"
:key="item"
class="button"
:class="{ 'button--active': equipment === item }"
:aria-pressed="equipment === item ? 'true' : 'false'"
@click="toggleEquipment(item)"
>
{{ item }}
</button>
</p>
<p>
Sort:
<button
v-for="option in sortOptions"
:key="option.value"
class="button"
:class="{ 'button--active': sort === option.value }"
@click="sort = option.value"
>
{{ option.label }}
</button>
</p>
<div class="search-box">
<label for="search">Search rooms</label>
<input
id="search"
v-model="searchText"
type="search"
placeholder="Search by name and press Enter"
@keyup.enter="applySearch"
@keyup.esc="clearSearch"
/>
<button class="button" :disabled="searchText === ''" @click="clearSearch">Clear</button>
</div>
</div>
</template>The important points:
- Five models with arguments, each a simple value. In the template, assigning a model (
floor = number,sort = option.value) emits the corresponding event: thedefineModelref is unwrapped in the template just like any other ref. equipmentOptionsis an ordinary prop, not a model: the filter only reads it (these are the available options, whichAppcalculates from the catalogue).- The search box combines two ideas from the previous lesson:
searchTextis a local copy (it changes with every keystroke without bothering anyone) andsearchis the model (it is only updated when Enter is pressed). Thewatchkeeps the copy in sync when the change comes from outside. - The search field keeps a fixed
id="search"because there will only be one filter on the page. IfRoomFiltershad to be used several times at once, it would be advisable to generate theidwithuseId(), asTextFielddoes.
8.3 BookingForm.vue: the form becomes independent
The booking form is the largest block in App.vue, with more than 120 lines of script. Create src/components/BookingForm.vue and move into its <script setup>, from App.vue, the whole // --- Booking form --- block: dayHours, availableExtras, toISODate, todayISO, toMinutes, createEmptyForm, form, touched, formRoom, durationHours, bookingPrice, errors, formIsValid, errorCount, markTouched, visibleError, resetForm and submitBooking. The bookings list and the roomNameById function stay in App.vue: the bookings created are none of the form's business.
Then adjust the beginning of the script and the functions that change:
// BookingForm.vue — beginning of the <script setup>
import { ref, reactive, computed, watch } from 'vue'
import TextField from './base/TextField.vue'
import { rooms } from '@/data/rooms.js'
// --- Public contract ---
const { roomId = 'panal', attendees = 1 } = defineProps({
roomId: String, // room the form starts with or switches to
attendees: Number // number of attendees proposed from outside
})
const emit = defineEmits({
create: (booking) => typeof booking.id === 'string' && typeof booking.roomId === 'string'
})
const today = new Date() // moves here from App.vue together with todayISO
// formatPrice: third copy (App, RoomCard and here) until the module 7 plugin
const euroFormatter = new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'EUR' })
function formatPrice(amount) {
return euroFormatter.format(amount)
}
// ... here, the block moved from App.vue, with these changes: ...// createEmptyForm: starts from the props, not from App's variables
function createEmptyForm() {
return {
roomId,
date: '',
startTime: '10:00',
endTime: '12:00',
member: '',
attendees,
status: 'confirmed',
extraEquipment: [],
notes: '',
acceptsRules: false
}
}
// When the parent proposes another room or other attendees, the form adopts them
// (place this after the declaration of form)
watch([() => roomId, () => attendees], ([newRoom, newAttendees]) => {
form.roomId = newRoom
form.attendees = newAttendees
})
// submitBooking: instead of storing the booking, it hands it over to the parent
function submitBooking() {
if (!formIsValid.value) return
const booking = {
id: crypto.randomUUID(),
roomId: form.roomId,
date: form.date,
startTime: form.startTime,
endTime: form.endTime,
member: form.member,
attendees: form.attendees,
status: form.status,
extraEquipment: [...form.extraEquipment],
notes: form.notes
}
emit('create', booking)
resetForm()
}- The
roomIdandattendeesprops replaceselectedRoomId.valueand the oldseats.booked: the form can no longer readApp's variables, so whatever it needs arrives as a prop. - The
watchwith two sources (getters, because they are destructured props) applies the parent's proposals to the form's state. Notice that the form keeps its own state (form, areactive) and that the props only propose values to it: this is the local copy pattern from 03-02, with a watcher to follow the changes. submitBookingno longer doesbookings.value.push(...): it emitscreatewith the booking. What is done with it (storing it in a list, sending it to the API) is the parent's decision.
In the template, move the whole <form> from App.vue (not the heading or the list of bookings) and replace the member, date and attendees fields with TextField:
<template>
<form class="form" novalidate @submit.prevent="submitBooking">
<TextField
v-model.trim="form.member"
label="Member name"
:error="visibleError('member')"
@blur="markTouched('member')"
/>
<!-- Room: the <div class="field"> with its <select>, no changes -->
<TextField
v-model="form.date"
input-type="date"
label="Date"
:error="visibleError('date')"
@blur="markTouched('date')"
/>
<!-- Time slot: no changes -->
<TextField
v-model.number="form.attendees"
input-type="number"
label="Attendees"
:error="visibleError('attendees')"
@blur="markTouched('attendees')"
/>
<!-- Status, extra equipment, notes, rules, summary and buttons: no changes -->
</form>
</template>Each field goes from about 15 lines to 6, and the hand-written ids and the repeated ARIA attributes disappear: TextField manages them now. Notice that v-model.trim and v-model.number still work without TextField doing anything special.
A few attributes have been lost along the way: autocomplete="name" and the name field's placeholder, the date's :min="todayISO" and the attendees' min/:max. If you add them to <TextField> now, they will end up on the root <div> (check this with the inspector), where they are useless. We will get them back in 03-05.
For the styles, move the form rules from App.vue to the <style scoped> of BookingForm.vue: .booking form (rename it to .form), .field, .field--times, fieldset.field, the input, select and textarea styles inside .field, [aria-invalid='true'], .error, .hint and .price-summary. The fields that are not TextFields (the room <select>, the times, the notes area) still need them.
8.4 App.vue as coordinator
In the script of App.vue:
import RoomFilters from './components/RoomFilters.vue'
import BookingForm from './components/BookingForm.vue'
// DELETE: capacityOptions, sortOptions, toggleEquipment, searchText,
// placeholder, applySearch, clearSearch, roomMatches, today and the whole
// form block (already moved). KEEP: search, normalize and matchesSearch,
// because visibleRooms still uses them.
// clearFilters: now it is enough to assign the data; RoomFilters updates itself
function clearFilters() {
minCapacity.value = 1
requiredEquipment.value = ''
sort.value = 'none'
search.value = ''
}
// --- Booking: App coordinates the catalogue and the form ---
const requestedAttendees = ref(1)
const bookings = ref([])
function prepareBooking({ roomId, attendees }) {
selectRoom(roomId)
requestedAttendees.value = Math.max(1, attendees)
}
function recordBooking(booking) {
bookings.value.push(booking)
console.log('[Colmena] Booking created:', booking)
}In the template, the catalogue section replaces its <div class="filters"> with the component, and the search box (which was outside the catalogue) disappears from App.vue:
<section class="catalog">
<h2>Catalogue</h2>
<RoomFilters
v-model:floor="floorFilter"
v-model:min-capacity="minCapacity"
v-model:equipment="requiredEquipment"
v-model:sort="sort"
v-model:search="search"
:equipment-options="catalogEquipment"
/>
<!-- Loading / error / empty / no results / data states and <RoomList>: no changes -->
</section>And the booking section ends up like this:
<section class="booking">
<h2>New booking</h2>
<BookingForm
:room-id="selectedRoomId"
:attendees="requestedAttendees"
@create="recordBooking"
/>
<h3>Bookings created in this session</h3>
<!-- The list of bookings, no changes -->
</section>Notice what has happened with floorFilter: it is still in App.vue, and the watch that reloads the catalogue from the API is still watching it. RoomFilters only edits it; App is still the owner and reacts to its changes exactly as before. And since :room-id is bound to selectedRoomId, selecting a room in the catalogue now also proposes it to the form.
8.5 Try it
- Use all the filters: the catalogue responds as before. In Vue DevTools, select
RoomFiltersand look at its props (floor,minCapacity...); in Timeline you will see theupdate:floor,update:sort... events. - Type in the search box without pressing Enter: nothing is emitted. Press Enter:
update:searchis emitted. Click "Clear filters" in the no-results state: the search field is emptied thanks to thewatch. - In the form, type spaces around the name and submit: the booking arrives trimmed (
.trim). Enter some attendees: in DevTools you will see thatform.attendeesis a number (.number). - Inspect the
<label>and the<input>of aTextField: they share anidgenerated byuseId()(a short string starting withv), different for each field. - Add 4 attendees on the Néctar card and click "Book": the form switches to Néctar with 4 attendees, thanks to the props and the form's
watch.
Common Mistakes and Tips
- Using
v-modeldirectly on a prop in the child (<input v-model="modelValue">with an ordinary prop). That is trying to modify a prop. UsedefineModelor the:value+ emit pair. - Mutating the properties of a model object (
model.value.floor = 2). The event is not emitted. Assign a new object or, better still, use severalv-models with simple values. - Writing the model's name in kebab-case in the script (
defineModel('min-capacity')). In the script it goes in camelCase; in the parent's template, in kebab-case. - Giving the model a
defaultwithout initialising the parent's data. Child and parent get out of sync. Always initialise the data in the parent. - Expecting
.lazyto work on a component. It is not applied automatically; if you need it, the internal control must listen tochange. - Putting the validation inside the generic field.
TextFielddisplays errors; whoever knows the rules (the form) decides on them. - Tip: if you are unsure whether to use a prop or
v-model, ask yourself who changes the data. If only the parent changes it, a prop. If the child is the control that edits it,v-model.
Exercises
Exercise 1. Create src/components/base/NumberStepper.vue, a control with a "−" button, the current number and a "+" button, which works with v-model and accepts the min (default 1) and max (default 99) props. The buttons must be disabled at the limits. Use it in BookingForm for the attendees, with :max="formRoom.capacity", instead of the numeric TextField.
Exercise 2. Implement a custom .capitalize modifier in TextField that capitalises the first letter of each word ("laura gómez" → "Laura Gómez"), and use it on the member field together with .trim. In what order are .trim and your modifier applied?
Exercise 3. A colleague has written this version of RoomFilters with a single model, and says that "it works". Explain why it is fragile and fix it without changing the way the parent uses it (v-model="filters").
<script setup>
const filters = defineModel({ type: Object, required: true })
</script>
<template>
<button v-for="number in 3" :key="number" @click="filters.floor = number">{{ number }}</button>
<button @click="filters.sort = 'price-asc'">Cheapest first</button>
</template>Solutions
Solution 1.
<!-- src/components/base/NumberStepper.vue -->
<script setup>
const value = defineModel({ type: Number, required: true })
const { min = 1, max = 99 } = defineProps({
min: Number,
max: Number
})
function step(delta) {
// Assigning the model emits update:modelValue; Math.min/max keep the value in range
value.value = Math.min(max, Math.max(min, value.value + delta))
}
</script>
<template>
<div class="number-stepper">
<button type="button" :disabled="value <= min" aria-label="One fewer" @click="step(-1)">
−
</button>
<output aria-live="polite">{{ value }}</output>
<button type="button" :disabled="value >= max" aria-label="One more" @click="step(1)">
+
</button>
</div>
</template><!-- BookingForm.vue -->
<div class="field">
<span>Attendees</span>
<NumberStepper v-model="form.attendees" :max="formRoom.capacity" />
<p v-if="visibleError('attendees')" class="error">{{ visibleError('attendees') }}</p>
</div>The buttons have type="button": inside a <form>, without it, they would submit the form. <output> with aria-live makes the screen reader announce the new number. Bear one detail in mind: if the user switches to a smaller room, the current value may exceed the new maximum; the form's errors validation will still detect it.
Solution 2.
// TextField.vue
const [model, modifiers] = defineModel({
type: [String, Number],
set(value) {
if (typeof value !== 'string') return value
if (modifiers.uppercase) return value.toUpperCase()
if (modifiers.capitalize) {
return value.replace(/(^|\s)(\p{L})/gu, (_, space, letter) => space + letter.toUpperCase())
}
return value
}
})The regular expression looks for a letter (\p{L}, any Unicode letter, including accented ones, thanks to the u flag) at the beginning of the text or after a space, and converts it to upper case. As for the order: first your set runs in the child (capitalising) and then, when the event is emitted, Vue applies .trim before handing the value to the parent.
Solution 3. filters.floor = number (in the template, filters is unwrapped) modifies a property of the parent's object without assigning the model, so update:modelValue is never emitted. It only "works" because the parent's object is reactive; but the parent cannot react to the event, it would fail with a readonly object and nobody reading the parent will know that the child modifies it. The fix: always assign a new object.
<script setup>
const filters = defineModel({ type: Object, required: true })
function update(changes) {
filters.value = { ...filters.value, ...changes } // assignment: emits update:modelValue
}
</script>
<template>
<button v-for="number in 3" :key="number" @click="update({ floor: number })">
{{ number }}
</button>
<button @click="update({ sort: 'price-asc' })">Cheapest first</button>
</template>Even so, the version with several v-models with arguments that we have built is preferable: each filter is a simple value, one event is emitted per filter and the parent can watch each one separately (as App does with floorFilter to reload the catalogue).
Conclusion
On a component, v-model is the pair formed by the modelValue prop and the update:modelValue event and, with an argument (v-model:floor), the pair floor + update:floor, which allows several models per component. defineModel() (3.4+) implements it for you: it returns a ref that reads the prop and that, when assigned, emits the event; it accepts type, required, default and get/set transformations, with which custom modifiers such as .uppercase are implemented, while .trim and .number work on their own. The manual implementation with prop + emit (or a writable computed property) is still present in a lot of code, and the golden rule is the same in both: the child assigns the model; it never mutates the properties of an object it has received. Colmena now has TextField (with useId for its accessibility), RoomFilters with five v-models and BookingForm, which emits create with the booking. App.vue no longer contains the form or the filters: it keeps the data and coordinates.
All our components, however, decide entirely what they render: the parent can pass them data, but not markup. What if we want a button with a different icon in each place, or want the room list to render each item differently depending on where it is used? For that, the parent needs to be able to inject its own content inside the child. That is the role of slots, which we will study in Slots, where we will also create BaseButton and BasePanel.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
