Unlike Vue 2, in Vue 3, we can use more than one v-model
directive. Each v-model
synchronizes with a different
property, simplifying the process of reactive communication between components:
<AppForm
v-model:name="name"
v-model:surname="surname"
v-model:profession="profession"
/>
v-model
Vue 3 Composition API
The key to using multiple v-model
with Vue 3 is to specify a modifier/argument when writing the directive, such
as v-model:<argument>
. Each argument points to a reactive property that resides in the parent component and is
intended to be passed to a child component.
From the child component, we declare the properties using the defineProps
helper:
const props = defineProps({
name: {
type: String,
required: true,
},
surname: {
...
},
profession: {
...
},
})
And define the events using the update:<prop>
naming convention and defineEmits
:
const emit = defineEmits([
'update:name',
'update:surname',
'update:profession',
]);
Now, we can confidently use the new properties coming from v-model
within the component's structure:
<template>
<article>
<div>
<label for="name">Name</label>
<input
:value="name"
@input="$emit('update:name', $event.target.value)"
type="text"
id="name"
/>
</div>
...
</article>
</template>
You can even create a local method to simplify the update process:
const updateProp = (prop, {target: {value}}) => emit(`update:${prop}`, value);