JAVASCRIPT

Custom `v-model` for Form Input Components

Implement the `v-model` directive on a custom Vue 3 component to create reusable and convenient form input elements with two-way data binding.

// CustomInput.vue
<template>
  <input
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
    placeholder="Enter text..."
  />
</template>

<script setup>
import { defineProps, defineEmits } from 'vue';

defineProps({
  modelValue: String, // The default prop name for v-model
});

defineEmits(['update:modelValue']); // The default event name for v-model
</script>

// App.vue (or any parent component)
<template>
  <div>
    <h1>Custom Input Example</h1>
    <CustomInput v-model="message" />
    <p>Message: {{ message }}</p>
    <button @click="message = 'Hello World'">Set Message</button>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import CustomInput from './CustomInput.vue';

const message = ref('Initial Message');
</script>
How it works: This snippet demonstrates how to implement `v-model` on a custom Vue 3 component, making it behave like a native input element for two-way data binding. By default, `v-model` uses a `modelValue` prop and an `update:modelValue` event. The `CustomInput.vue` component defines the `modelValue` prop to receive the data and emits `update:modelValue` whenever its internal input changes. The parent component then uses `v-model="message"` on `CustomInput`, abstracting away the explicit prop passing and event listening, resulting in cleaner and more intuitive form interactions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs