Search code examples
javascriptvue.jsvuejs2vue-componentvuetify.js

Vuetify - using change event assign the selected item to a data property


I have a v-select that looks like this:

    <v-select
      v-model="editedItem.site_id"
      :items="sites"
      label="Sites"
      item-text="name"
      item-value="id"
    ></v-select>

The sites items look like this:

0:
    city: (...)
    client: Object
        created_at: "2020-08-20T11:11:12.000000Z"
        created_by: "..."
        deleted_at: null
        id: 1
        name: "Lemmer"
        updated_at: "2020-08-24T03:53:39.000000Z"
        updated_by: "..."
    client_id: (...)
    country: (...)
    country_id: (...)
    created_at: (...)
    created_by: (...)
    deleted_at: (...)
    id: (...)
    name: (...)
    office: (...)
    street: (...)
    updated_at: (...)
    updated_by: (...)
    zipcode: (...)

So now I want to put the on a @change event the sites.client.name in the var. What is here the best way?

I tried this:

<v-select
  v-model="editedItem.site_id"
  :items="sites"
  label="Sites"
  item-text="name"
  item-value="id"
  @change="clientname = sites.client.name"
></v-select>

But I get the this error:

[Vue warn]: Error in v-on handler: "TypeError: Cannot read property 'name' of undefined"

Solution

  • In your case, you cannot use site.name because if you make item-value="id", site value will be the same as id. I made a simple codepen for your issue. Please reference it. https://codepen.io/plsdev89/pen/OJNpmyG

    <label>Client name: {{clientname}}</label>
    <v-select
       :items="sites"
       label="Sites"
       item-text="name"
       item-value="id"
       @change="handleSiteChange"
     ></v-select>
    ...
    handleSiteChange(id) {
      let site = this.sites.filter(item => item.id === id);
      if(site.length > 0) {
        this.clientname = site[0].name;
      }
    }