Categories
Vue Answers

How to assign object to model with Vue Vuetify v-autocomplete?

Spread the love

To assign an object to a model with v-autocomplete in Vue.js with Vuetify, you typically use the item-value and item-text properties to specify which properties of the objects in your items array should be used for the model’s value and text display. Here’s an example:

<template>
  <v-autocomplete
    v-model="selectedItem"
    :items="items"
    item-value="id"
    item-text="name"
    label="Select Item"
    return-object
  ></v-autocomplete>
</template>

<script>
export default {
  data() {
    return {
      selectedItem: null,
      items: [
        { id: 1, name: 'Item 1' },
        { id: 2, name: 'Item 2' },
        { id: 3, name: 'Item 3' }
      ]
    };
  }
};
</script>

In this example we have v-model="selectedItem" binds the selected object to the selectedItem data property.

:items="items" specifies the array of items to choose from.

item-value="id" indicates that the id property of each item object should be used as the model value.

item-text="name" specifies that the name property of each item object should be displayed as the text in the autocomplete dropdown.

return-object indicates that the v-model will return the selected object instead of just the value.

With this setup, when the user selects an item from the autocomplete dropdown, selectedItem will be assigned the corresponding object from the items array.

We can then access the selected object through selectedItem in your Vue component.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *