JAVASCRIPT
Creating Custom Form Inputs with `v-model` in Vue 3
Develop reusable custom form input components that fully integrate with Vue 3's `v-model` directive using `props` and `emits` for two-way data binding.
// src/components/MyCustomInput.vue
<template>
<label>
{{ label }}:
<input
type="text"
:value="modelValue"
@input="updateValue($event.target.value)"
class="custom-input"
/>
</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']);
const updateValue = (value) => {
emit('update:modelValue', value);
};
</script>
<style scoped>
.custom-input {
border: 1px solid #ccc;
padding: 8px;
border-radius: 4px;
margin-left: 5px;
}
</style>
// src/App.vue (example usage)
<template>
<div>
<h1>Custom Input Example</h1>
<MyCustomInput v-model="userName" label="Your Name" />
<p>Your Name: {{ userName }}</p>
<MyCustomInput v-model="userEmail" label="Your Email" />
<p>Your Email: {{ userEmail }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyCustomInput from './components/MyCustomInput.vue';
const userName = ref('');
const userEmail = ref('');
</script>
How it works: This snippet demonstrates how to create a custom form input component that seamlessly integrates with Vue 3's `v-model` directive. The `MyCustomInput.vue` component defines a `modelValue` prop to receive the value and emits an `update:modelValue` event to update the parent's bound data. This convention allows the parent component (`App.vue`) to use `v-model` directly on the custom input, enabling two-way data binding. This pattern is crucial for building reusable and maintainable form components in Vue applications.