Question
Answer and Explanation
Using v-autocomplete
with v-model
as an object in Vuetify 3 is a powerful way to manage selected items when each item has multiple properties. Instead of just storing the selected value (e.g., a string), you store the entire object. This is particularly useful when you need access to multiple fields from the selected option.
Here's a complete example demonstrating how to do this:
First, let's consider the data structure. You'll have an array of objects, where each object represents an item in the autocomplete list. For instance:
const items = [
{ id: 1, name: 'John Doe', email: 'john.doe@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' },
{ id: 3, name: 'Peter Jones', email: 'peter.jones@example.com' },
];
Now, let's look at the Vuetify component in a Vue 3 single file component or a template:
<template>
<v-autocomplete
:items="items"
item-title="name"
item-value="id"
v-model="selectedItem"
label="Select a Person"
></v-autocomplete>
<div v-if="selectedItem">
<p class="qa-text">Selected Name: {{ selectedItem.name }}</p>
<p class="qa-text">Selected Email: {{ selectedItem.email }}</p>
</div>
</template>
<script setup>
import { ref } from 'vue';
const items = ref([
{ id: 1, name: 'John Doe', email: 'john.doe@example.com' },
{ id: 2, name: 'Jane Smith', email: 'jane.smith@example.com' },
{ id: 3, name: 'Peter Jones', email: 'peter.jones@example.com' },
]);
const selectedItem = ref(null);
</script>
Key Points:
- `items`: Array of objects, which is the source data for the autocomplete list.
- `item-title="name"`: Specifies which property of the item object should be displayed in the autocomplete list. Here, it's the name
property.
- `item-value="id"`: Specifies which property to use as the value when an item is selected. Here, it's the id
property. This is crucial so that when an option is chosen, the whole corresponding object is assigned to `selectedItem`.
- `v-model="selectedItem"`: The `v-model` is bound to a reactive ref
, selectedItem
, which will hold the full selected object when a selection is made from the dropdown.
When a user selects an item from the autocomplete, the entire object corresponding to the selected value (which is the `id` property of the selected item) is assigned to selectedItem
. You can then access other properties of the selected object (like name
or email
) as demonstrated in the example within the template.
This method allows you to handle more complex selections with rich data by storing the entire selected object instead of just a single value. It is especially useful for scenarios where multiple properties need to be accessed or used after a user makes a selection.