JAVASCRIPT
Customizing Multiple `v-model` Bindings for Vue 3 Components
Learn how to use multiple `v-model` bindings on a single Vue 3 component to manage different properties, enhancing component reusability and clarity for complex forms.
<!-- ChildComponent.vue -->
<template>
<div>
<label>
First Name:
<input type="text" :value="firstName" @input="$emit('update:firstName', $event.target.value)" />
</label>
<br />
<label>
Last Name:
<input type="text" :value="lastName" @input="$emit('update:lastName', $event.target.value)" />
</label>
</div>
</template>
<script setup>
const props = defineProps({
firstName: String,
lastName: String,
});
const emit = defineEmits(['update:firstName', 'update:lastName']);
</script>
<!-- ParentComponent.vue -->
<template>
<div>
<h2>Parent Component</h2>
<p>User: {{ user.firstName }} {{ user.lastName }}</p>
<ChildComponent v-model:firstName="user.firstName" v-model:lastName="user.lastName" />
</div>
</template>
<script setup>
import { reactive } from 'vue';
import ChildComponent from './ChildComponent.vue';
const user = reactive({
firstName: 'John',
lastName: 'Doe',
});
</script>
How it works: Vue 3 allows components to support multiple `v-model` bindings by explicitly defining which prop they target. In the `ChildComponent`, we define `firstName` and `lastName` props. Instead of the default `update:modelValue` event, we emit `update:firstName` and `update:lastName` respectively. The `ParentComponent` then uses `v-model:firstName` and `v-model:lastName` to bind to specific properties of its `user` reactive object, making the component highly reusable for managing complex data.