Vue3 Fundamentals ยท Components, Props & Events

Custom v-model on a component

Custom v-model on a component

v-model on an input is two-way binding. On a component, it is a convention: Vue expects the component to accept a modelValue prop and to emit an update:modelValue event when that value should change.

You build it from the two pieces you already know:

<script setup>
defineProps(['modelValue']);
const emit = defineEmits(['update:modelValue']);
</script>

<template>
  <input :value="modelValue" @input="emit('update:modelValue', $event.target.value)" />
</template>

The prop carries the current value down; the event carries the new value back up. A parent writes <Field v-model="name" />, and Vue wires the pair together: it passes name as modelValue and listens for update:modelValue.

The names matter. modelValue and update:modelValue are the convention Vue recognises; any other pair is an ordinary prop and event. Because the component only reads modelValue and emits the change, the parent keeps ownership of the value. The Test sets the input's value and checks the component emitted the new value.

Challenge

The input cannot send its value back to a parent. Build a two-way component: export an App component from App.vue that accepts a modelValue prop and emits update:modelValue with the input's new value when it changes.

The Test mounts your component with modelValue set to Vue, types Vue 3 into the input, and checks the component emitted update:modelValue with Vue 3. The starter has no binding or event, so the Test fails.

App.vue
<script setup>
const label = 'Name';
</script>

<template>
  <input :aria-label="label" />
</template>

No test run yet

The Test is hidden. Run it to check the Challenge โ€” you only see the result, never the test source.