← Back to all snippets
JAVASCRIPT

Custom V-Model for Two-Way Data Binding on Components

Implement custom `v-model` functionality on your Vue 3 components to enable seamless two-way data binding for complex input or interactive elements.

// MyCustomInput.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 prop that receives the v-model value
});

defineEmits(['update:modelValue']); // The event emitted to update v-model
</script>

// How to use in ParentComponent.vue:
// <template>
//   <div>
//     <p>Parent Value: {{ parentText }}</p>
//     <MyCustomInput v-model="parentText" />
//   </div>
// </template>
//
// <script setup>
// import { ref } from 'vue';
// import MyCustomInput from './MyCustomInput.vue';
//
// const parentText = ref('Initial Text');
// </script>
How it works: This snippet shows how to implement custom `v-model` behavior for a component in Vue 3. By default, `v-model` on a component binds to the `modelValue` prop and listens for the `update:modelValue` event. The `MyCustomInput` component defines a `modelValue` prop to receive the data and emits `update:modelValue` with the new value whenever the input changes. This allows `ParentComponent` to use `v-model="parentText"` for clean two-way data binding with `MyCustomInput`, just like native HTML inputs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs