JAVASCRIPT

Custom v-model for Vue 3 Components

Learn to implement custom v-model on your Vue 3 components, allowing two-way data binding with custom props and events for enhanced reusability and control.

<!-- MyCustomInput.vue -->
<template>
  <div class="custom-input-wrapper">
    <label v-if="label">{{ label }}</label>
    <input
      type="text"
      :value="modelValue"
      @input="$emit('update:modelValue', $event.target.value)"
      class="custom-input"
    />
  </div>
</template>

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

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

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

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

<!-- App.vue (Usage) -->
<template>
  <div>
    <h1>Custom v-model Example</h1>
    <MyCustomInput v-model="message" label="Your Message:" />
    <p>Message: {{ message }}</p>

    <MyCustomInput v-model:name="userName" label="Your Name:" />
    <p>User Name (named v-model): {{ userName }}</p>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import MyCustomInput from './MyCustomInput.vue'; // Assuming MyCustomInput.vue is in the same directory

const message = ref('Hello Vue!');
const userName = ref('John Doe'); // For named v-model example
</script>
How it works: This snippet demonstrates how to implement `v-model` on a custom Vue 3 component. By default, `v-model` binds to a `modelValue` prop and emits an `update:modelValue` event. The `MyCustomInput` component accepts `modelValue` as a prop and emits the updated value using `$emit('update:modelValue', ...)` whenever its internal input changes, enabling seamless two-way data binding with parent components. It also briefly shows how to use named `v-model` for multiple bindings.

Need help integrating this into your project?

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

Hire DigitalCodeLabs