JAVASCRIPT

Implement Custom v-model for Reusable Vue 3 Components

Discover how to create custom form inputs in Vue 3 that support `v-model` for two-way data binding, enhancing component reusability and developer experience.

// CustomInput.vue
<template>
  <input
    :value="modelValue"
    @input="$emit('update:modelValue', $event.target.value)"
    class="custom-input"
    placeholder="Type something..."
  />
</template>

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

defineProps({
  modelValue: {
    type: String,
    default: ''
  }
});

defineEmits(['update:modelValue']);
</script>

<style scoped>
.custom-input {
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
}
</style>

// App.vue (Parent Component)
<template>
  <div>
    <h1>Custom V-Model Example</h1>
    <CustomInput v-model="message" />
    <p>Message: {{ message }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import CustomInput from './components/CustomInput.vue'; // Adjust path as needed

const message = ref('Hello Vue!');
</script>
How it works: This snippet shows how to implement custom `v-model` functionality for a reusable Vue 3 component. By default, `v-model` on a component binds to a `modelValue` prop and listens for an `update:modelValue` event. The `CustomInput` component accepts `modelValue` as a prop and emits `update:modelValue` with the new input value whenever its native input changes. This allows the parent component to use `v-model="message"` for two-way data binding, simplifying data flow and enhancing reusability for custom form controls.

Need help integrating this into your project?

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

Hire DigitalCodeLabs