I am using a v-autocomplete component to search for places on the google api. So the items array gets filled after the search input is set. Now I'm trying to set a default value to be searched before the user makes an input to suggest a train station.
E.g. the search is opened for the city London, now I wan't to set the search input to London Train Station so the user sees the results for that search. However, when I set the search input to a default value it get's reset to null every time.
Here is my template:
<v-autocomplete
ref="trainStationSearch"
v-model="select"
:items="places"
:search-input.sync="searchTerm"
no-filter
return-object
>
<template #item="data">
<v-list-item-content>
<v-list-item-title>{{ data.item.title }}</v-list-item-title>
<v-list-item-subtitle>{{ data.item.subtitle }}</v-list-item-subtitle>
</v-list-item-content>
</template>
</v-autocomplete>
And here the logic:
- I have a watcher on
searchTerm, which triggers a debounced search with Lodash'sdebouncefunction - I try to set
searchTermin themountedhook with the value of the propprefill- Doing it with the timeout triggers the watcher on
searchTermand shows the value ofprefillon the input of thev-autocompletecomponent. Shortly aftersearchTermis reset tonull - Doing it without a timeout results in
searchTermbeing set tonullimmediately
- Doing it with the timeout triggers the watcher on
@Prop() readonly prefill?: string
private places: any = []
private searchTerm: string | null = ''
private select: any = null
private searchGoogle = _.debounce(
async (val: string, context: Vue): Promise<void> => {
if (val) {
// doing the request to my API, which returns the google results
const data = await apiManager.searchPlaces(val)
// set the items array to the google results
this.$set(context, 'places', data.predictions)
}
},
1000
)
@Watch('searchTerm')
private searchPlaces(val: string): void {
if (val?.trim().length > 0) {
// trigger debounced request
this.searchGoogle(val, this)
} else {
// empty places array
this.places.splice(0, this.places.length)
}
}
@Watch('select')
private handleSelection(): void {
if (!this.select) {
return
}
// handle selection
}
private mounted() {
if (this.prefill) {
setTimeout(() => {
this.searchTerm = this.prefill!
}, 1000)
}
}