JAVASCRIPT

Vue 3 `v-model` with Custom Component

Learn to implement two-way data binding with Vue 3's `v-model` directive for both native HTML inputs and your own custom components, enhancing reusability.

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

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

defineProps({
  modelValue: String,
});

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

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

// ParentComponent.vue
<template>
  <div>
    <p>Parent Value: {{ message }}</p>
    <MyCustomInput v-model="message" />
    <input type="text" v-model="message" placeholder="Native input example" />
  </div>
</template>

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

const message = ref('Hello Vue!');
</script>
How it works: This snippet demonstrates how to use Vue 3's `v-model` directive for two-way data binding. For native HTML inputs, `v-model` works out of the box. For custom components, `v-model` is a syntactic sugar that expands to a `modelValue` prop and an `update:modelValue` event. The `MyCustomInput` component accepts a `modelValue` prop and emits an `update:modelValue` event whenever its input changes, allowing the `ParentComponent` to keep its `message` reactive reference synchronized with the custom input's value.

Need help integrating this into your project?

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

Hire DigitalCodeLabs