JAVASCRIPT
Vue 3 Custom `v-model` for Component Input
Learn how to implement `v-model` functionality on your custom Vue 3 components, enabling two-way data binding for enhanced reusability and clean form handling.
// src/components/MyCustomInput.vue
<template>
<label>
{{ label }}:
<input
type="text"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
/>
</label>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
const props = defineProps({
modelValue: {
type: String,
default: ''
},
label: {
type: String,
default: 'Input'
}
});
const emit = defineEmits(['update:modelValue']);
</script>
// src/App.vue
<template>
<div>
<h1>Custom V-Model Example</h1>
<MyCustomInput v-model="message" label="Your Message" />
<p>Parent Component Message: {{ message }}</p>
<hr />
<MyCustomInput v-model:modelValue="username" label="Username" />
<p>Parent Component Username: {{ username }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyCustomInput from './components/MyCustomInput.vue';
const message = ref('Hello Vue!');
const username = ref('JohnDoe');
</script>
How it works: This snippet shows how to create a custom input component (`MyCustomInput.vue`) that fully supports Vue 3's `v-model`. By defining a `modelValue` prop and emitting an `update:modelValue` event on input, the custom component achieves seamless two-way data binding with the parent component, making it behave like a native input element.