We previously learned how v-model perfectly binds simple text fields and checkboxes.
However, modern applications often require complex, custom-built form components like searchable dropdowns or toggle switches.
Vue allows you to use v-model on your very own custom components!
To make a custom component compatible with v-model, we must understand how it operates.
When you use v-model="searchText", Vue actually expands it into two separate actions:
modelValue to the component.update:modelValue to catch changes.To build a custom input, your child component must accept the modelValue prop.
Then, when the user types or clicks, it must $emit the update:modelValue event containing the new data.
<!-- ChildComponent.vue -->
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</template>
<script setup>
defineProps(['modelValue'])
defineEmits(['update:modelValue'])
</script>
Sometimes a single custom component needs to bind multiple different values.
For example, a <UserNameInput> might need to bind both a firstName and a lastName.
Vue 3 allows you to target specific prop names by appending a colon: v-model:firstName="first".
<!-- Parent Component --> <UserNameInput v-model:firstName="first" v-model:lastName="last" />
This flexibility is why Vue is universally loved for building complex form architectures!
When you place v-model on a custom component, what is the default prop name Vue passes down?
What exact event must the custom child component emit to update the v-model value?