Form inputs often have separate fields that belong together, for example the “name” field may be decomposed into “first name” and “last name”. This guide shows you how to bundle multiple fields into a single component. The objective is to have the input’s value represented as an object:
{
"firstName": "First name value",
"lastName": "Last name value",
}
First, create a single page component called “Name.vue” containing two inputs:
<template>
<div>
<input type="text" v-model="value.firstName" />
<input type="text" v-model="value.lastName" />
</div>
</template>
<script setup>
const props = defineProps({ modelValue: Object });
const value = props.modelValue;
</script>
The component is used as follows:
<template>
<div>
<name v-model="name"></name>
<br />
{{ name }}
</div>
</template>
<script setup>
import { ref } from "vue";
import Name from "@/Name.vue";
const name = ref({ firstName: "Test", lastName: "Person" });
</script>