JAVASCRIPT
Implementing Custom `v-model` for Reusable Input Components
Learn how to create custom Vue 3 components that support `v-model`, enabling two-way data binding for enhanced reusability and clean form integration within your applications.
// MyCustomInput.vue
<template>
<input
type="text"
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
class="custom-input"
placeholder="Type something..."
/>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
modelValue: String
});
defineEmits(['update:modelValue']);
</script>
<style scoped>
.custom-input {
border: 1px solid #ccc;
padding: 8px;
border-radius: 4px;
}
</style>
// ParentComponent.vue
<template>
<div>
<MyCustomInput v-model="message" />
<p>Input Value: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyCustomInput from './MyCustomInput.vue';
const message = ref('Hello Vue!');
</script>
How it works: This snippet demonstrates how to build a custom input component that works seamlessly with Vue 3's `v-model`. The child component `MyCustomInput` accepts a `modelValue` prop and emits an `update:modelValue` event when its internal input changes. The parent component then uses `v-model="message"` on `MyCustomInput`, which automatically handles passing `message` as `modelValue` and updating `message` when `update:modelValue` is emitted, simplifying two-way data binding for custom components.