JAVASCRIPT
Implementing Custom Two-Way Data Binding with Vue 3 `v-model`
Build flexible and reusable components by implementing custom `v-model` for two-way data binding using Vue 3's Composition API, simplifying parent-child communication.
<!-- MyCustomInput.vue -->
<template>
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
placeholder="Type something..."
/>
</template>
<script setup>
import { defineProps, defineEmits } from 'vue';
defineProps({
modelValue: {
type: String,
default: ''
}
});
defineEmits(['update:modelValue']);
</script>
<!-- App.vue -->
<template>
<div>
<p>Parent Value: {{ myValue }}</p>
<MyCustomInput v-model="myValue" />
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyCustomInput from './MyCustomInput.vue';
const myValue = ref('Initial Text');
</script>
How it works: This snippet demonstrates how to implement a custom `v-model` for a component in Vue 3. A component implicitly supports `v-model` by accepting a `modelValue` prop and emitting an `update:modelValue` event. The parent component then uses `v-model="myValue"` on `MyCustomInput`, which automatically binds `myValue` to the `modelValue` prop and listens for `update:modelValue` events to update `myValue` accordingly, establishing seamless two-way data binding.