JAVASCRIPT
Customizing v-model for Reusable Vue 3 Input Components
Learn to implement `v-model` on your custom Vue 3 components, enabling seamless two-way data binding. This snippet creates a reusable text input component.
// src/components/CustomInput.vue
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
type="text"
class="custom-input"
placeholder="Enter text..."
/>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
modelValue: {
type: String,
default: ''
}
});
defineEmits(['update:modelValue']);
</script>
<style scoped>
.custom-input {
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
// src/App.vue
<template>
<div>
<h1>Custom Input Example</h1>
<CustomInput v-model="message" />
<p>Message: {{ message }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import CustomInput from './components/CustomInput.vue';
const message = ref('Hello World');
</script>
How it works: This snippet demonstrates how to customize `v-model` for a custom Vue 3 component. The `CustomInput.vue` component accepts a `modelValue` prop and emits an `update:modelValue` event. This pattern allows parent components to use `v-model` directly on `CustomInput`, providing convenient two-way data binding similar to native HTML input elements, making components highly reusable.