Custom v-model lets you connect a parent and child component easily. It helps sync data between them without extra code.
0
0
Custom v-model on components in Vue
Introduction
You want a child component to update a value in the parent automatically.
You build a reusable input component that works like a normal input with <code>v-model</code>.
You want to customize the event or prop name used for two-way binding.
You want to keep your template clean and simple when passing data back and forth.
Syntax
Vue
<script setup> const props = defineProps({ modelValue: String }) const emit = defineEmits(['update:modelValue']) function updateValue(newValue) { emit('update:modelValue', newValue) } </script> <template> <input :value="modelValue" @input="e => updateValue(e.target.value)" /> </template>
The prop modelValue holds the value from the parent.
The event update:modelValue sends changes back to the parent.
Examples
Basic usage:
v-model binds text to the child component's modelValue prop and listens for update:modelValue event.Vue
<MyInput v-model="text" />Using a custom prop and event name with
v-model:custom.Vue
<MyInput v-model:custom="text" /> // In child component: const props = defineProps({ custom: String }) const emit = defineEmits(['update:custom'])
Sample Program
This example shows a parent component using CustomInput with v-model. When you type in the input, the text updates in the parent and shows below.
Vue
<script setup> import { ref } from 'vue' const text = ref('Hello') </script> <template> <CustomInput v-model="text" /> <p>You typed: {{ text }}</p> </template> <!-- CustomInput.vue --> <script setup> const props = defineProps({ modelValue: String }) const emit = defineEmits(['update:modelValue']) function onInput(event) { emit('update:modelValue', event.target.value) } </script> <template> <input :value="modelValue" @input="onInput" aria-label="Custom input" /> </template>
OutputSuccess
Important Notes
Always use modelValue as the prop and update:modelValue as the event for default v-model.
You can add aria-label for accessibility on inputs.
Customizing v-model names helps avoid conflicts in complex components.
Summary
Custom v-model connects parent and child data easily.
Use modelValue prop and update:modelValue event by default.
Custom names are possible with v-model:customName.