code-8
code-8

Reputation: 58652

Dynamically update combobox list based on API response

enter image description here

I have a combobox of cities

<v-combobox
    v-model="city"
    :items="cities"
    item-text="name"
    label="City"
    v-on:keyup="getCities(city)"
></v-combobox>

I'm trying to call the API to as users typing ...

Ex. if user enter bos

I will sent bos to API and I will back a response back, I would like to update my list.

I can't seem to access this.city model value.


Note: : As soon as I change v-combobox to v-textfield, I can access this.city model value. But my goal is to use combobox.

Do you spot anything that I miss ?

Upvotes: 0

Views: 1263

Answers (1)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27192

Observations/Suggestions :

  • As per my understanding cities is an array of objects. If Yes, You have to use item-value to bind the values for the options.

  • Your issue is related to the return-object property which is apparently true by default. Disabling it causes the v-combobox to work as expected.

  • Instead of passing city inside getCities method as a parameter. You can directly access the v-model value using this keyword.

    getCities() {
        console.log(this.city);
    }
    
  • I will suggest you to use @change event instead of @keyup as user might select the value from the dropdown instead of typing. Hence, @keyup will not trigger in that case.

Demo :

new Vue({
  el: '#app',
  vuetify: new Vuetify(),
  data () {
    return {
      city: null,
      cities: [{
        name: 'Foo'
      },
      {
        name: 'Bar'
      }]
    }
  },
  methods: {
    getCities() {
      console.log(this.city)
    }
  }
})
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<script src="https://unpkg.com/[email protected]/dist/vuetify.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/vuetify.min.css"/>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"/>
<link rel="stylesheet" href="https://unpkg.com/@mdi/[email protected]/css/materialdesignicons.min.css"/>
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-row>
        <v-col cols="12">
          <v-combobox
            v-model="city"
            :items="cities"
            label="City"
            item-text="name"
            item-value="name"
            @change="getCities"
            :return-object="false"
            outlined
            dense
          ></v-combobox>
        </v-col>
      </v-row>
    </v-container>
  </v-app>
</div>

Upvotes: 1

Related Questions