JAVASCRIPT
Creating a Custom v-model for Component Props
Build reusable Vue 3 components that support `v-model` for flexible two-way data binding by properly handling the `modelValue` prop and `update:modelValue` emit event.
// MyInput.vue
<template>
<input
type="text"
: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>Input Value: {{ myText }}</p>
<MyInput v-model="myText" />
<button @click="myText = 'Hello World'">Set 'Hello World'</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
import MyInput from './MyInput.vue';
const myText = ref('Initial Text');
</script>
How it works: Vue 3's `v-model` syntax on a custom component simplifies two-way data binding. This snippet shows how to implement it: the child component (`MyInput.vue`) accepts a `modelValue` prop and emits an `update:modelValue` event whenever its internal value changes. The parent component (`App.vue`) then uses `v-model` on `MyInput`, which automatically handles the prop passing and event listening, synchronizing `myText` with the input's value.