JAVASCRIPT
Creating a Custom v-model Component in Vue 3
Learn how to build a reusable Vue 3 component that supports the v-model directive, enabling two-way data binding for custom inputs or elements, enhancing component interaction.
// MyCustomInput.vue
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
type="text"
class="custom-input"
/>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
modelValue: { type: String, default: '' },
});
defineEmits(['update:modelValue']);
</script>
<style scoped>
.custom-input {
padding: 8px 12px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
// ParentComponent.vue
<template>
<div>
<p>Message: {{ myMessage }}</p>
<MyCustomInput v-model="myMessage" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyCustomInput from './MyCustomInput.vue';
const myMessage = ref('Hello Vue 3!');
</script>
How it works: In Vue 3, the `v-model` directive on a custom component automatically binds to a `modelValue` prop and emits an `update:modelValue` event. This snippet demonstrates how to create `MyCustomInput.vue` to support this behavior. The component accepts `modelValue` as a prop and, when its internal input changes, it emits an `update:modelValue` event with the new value. The `ParentComponent` then uses `v-model="myMessage"` to establish two-way data binding with `MyCustomInput`, keeping `myMessage` reactive to the custom input's changes.