Skip to the workspace
Pebellslearn by building
Forms Handling  ›  Capstone Project

v-model on Your Own Components

v-model 14 mindefineModel lets a child component support v-model, returning a ref that reads the parent's value and writes changes back.

vue / v-model on Your Own Components

Explore each scene at your own pace.

01 · The rule

The rule

v-model on Your Own Components

Shelf's Add Book form needs a star rating. You build a StarRating component with five clickable stars, and you want to use it exactly like an input: <StarRating v-model="rating" />. For that, the component must follow the v-model contract. Since Vue 3.4, defineModel does the wiring in one line.

The rule

On a component, v-model is a modelValue prop plus an update:modelValue event; defineModel handles both.

The child:

<!-- StarRating.vue -->
<script setup>
const rating = defineModel({ type: Number, default: 0 })
</script>

<template>
  <div class="stars">
    <button v-for="n in 5" :key="n" type="button"
            :class="{ filled: n <= rating }"
            @click="rating = n">★</button>
  </div>
</template>

The parent:

<script setup>
import { ref } from 'vue'
import StarRating from './StarRating.vue'
const rating = ref(3)
</script>

<template>
  <StarRating v-model="rating" />
  <p>You gave it {{ rating }} stars.</p>
</template>

What happens underneath: on a component, v-model="rating" expands to

<StarRating :modelValue="rating" @update:modelValue="v => rating = v" />

defineModel() declares that prop and that event for you and returns a ref. Reading it gives the parent's current value. Assigning to it, as rating = n in the template or rating.value = n in script, emits update:modelValue with the new value, and the parent's ref updates. The child never mutates a prop; it asks, and the parent's v-model listener makes the change. This is still "props down, events up", just packaged.

Several models. Give the model a name to bind more than one value: defineModel('title') in the child pairs with v-model:title="book.title" in the parent. A component can have v-model:title and v-model:rating side by side.

Before Vue 3.4, you wrote the contract by hand: defineProps(['modelValue']) plus defineEmits(['update:modelValue']), and emit('update:modelValue', n) on click. You will still see this in older code, and it behaves the same.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.