Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuetify autocomplete - how to pass default value?

I'm using Vuetify autocomplete component and I want it to display a default value in its input field

I tried to pass just value as prop and change v-model field to any string but it doesn't work - an input field is empty unless I choose value form the list

Vuetify official example

<v-autocomplete
        v-model="select"
        :loading="loading"
        :items="items"
        :search-input.sync="search"
        cache-items
        class="mx-3"
        flat
        hide-no-data
        hide-details
        label="What state are you from?"
        solo-inverted
      ></v-autocomplete>

new Vue({
  el: '#app',
  data () {
    return {
      loading: false,
      items: [],
      search: null,
      select: 'Alabama',
      states: [
        'Alabama',
        'Alaska',
        'American Samoa',
        'Arizona',
        'Arkansas',
        'California',
        'Colorado',
      ]
    }
  },
  watch: {
    search (val) {
      val && val !== this.select && this.querySelections(val)
    }
  },
  methods: {
    querySelections (v) {
      this.loading = true
      // Simulated ajax query
      setTimeout(() => {
        this.items = this.states.filter(e => {
          return (e || '').toLowerCase().indexOf((v || '').toLowerCase()) > -1
        })
        this.loading = false
      }, 500)
    }
  }
})
like image 748
Person Avatar asked May 13 '19 11:05

Person


3 Answers

I ran into this and what I did was passing to the v-model, the element at the 0 index position from the list:

:items="items"
v-model="items[0]"
like image 87
StvnSpnz Avatar answered Oct 04 '22 23:10

StvnSpnz


The v-autocomplete component will not display "Alabama" since "Alabama" is not found in items. All you need to do is add "Alabama" to items to make it initially valid:

data () {
    return {
      loading: false,
      items: ['Alabama'], // <- add the default here
      search: null,
      select: 'Alabama',
      states: [ ...
like image 20
chris Avatar answered Oct 04 '22 23:10

chris


you can also use auto-select-first attribute along with default value in data.

   <v-autocomplete
          v-model="selectedItem"
          auto-select-first
          :items="items">
   </v-autocomplete>

  data() {
    return {
      items: ['Default'],
      selectedItem: "Default",
    }
}
like image 34
Pradeep N.V.S Avatar answered Oct 04 '22 21:10

Pradeep N.V.S