Vuetify : throttle / debounce v-autocomplete

11,554

Solution 1

You could add debouncing to the function that makes the API calls. A debouncer could be implemented with setTimeout and clearTimeout, such that new calls are delayed and cancels any pending call:

methods: {
  fetchEntriesDebounced() {
    // cancel pending call
    clearTimeout(this._timerId)

    // delay new call 500ms
    this._timerId = setTimeout(() => {
      this.fetch()
    }, 500)
  }
}

Such a method could be bound to a watcher on the search-input prop of v-autocomplete:

<template>
  <v-autocomplete :search-input.sync="search" />
</template>

<script>
export default {
  data() {
    return {
      search: null
    }
  },
  watch: {
    search (val) {
      if (!val) {
        return
      }

      this.fetchEntriesDebounced()
    }
  },
  methods: { /* ... */ }
}
</script>

demo

Solution 2

Thank you so much. It works. Here is my code (to geocode an adress) :

<v-autocomplete
        ref="refCombobox"
        v-model="adresseSelectionnee"
        :items="items"
        :loading="isLoading"
        :search-input.sync="search"
        no-filter
        hide-details
        hide-selected
        item-text="full"
        item-value="address"
        placeholder="Où ?"
        append-icon="search"
        return-object
        dense
        solo
        class="caption"
        clearable
        hide-no-data
      ></v-autocomplete>


watch: {

    search(val) {
      if (!val) {
        return;
      }

      this.geocodeGoogle(val);
    }
  },



methods: {
    geocodeGoogle(val) {
      // cancel pending call
      clearTimeout(this._timerId);

      this.isLoading = true;

      // delay new call 500ms
      this._timerId = setTimeout(() => {
        const geocoder = new this.$google.maps.Geocoder();
        geocoder.geocode({ address: val, region: "FR" }, (results, status) => {
          if (status === "OK") {
            this.adressesGoogle = results;
            this.isLoading = false;
          } else {               
            this.isLoading = false;
          }
        });
      }, 500);
    },
Share:
11,554

Related videos on Youtube

Ricou
Author by

Ricou

Updated on June 15, 2022

Comments

  • Ricou
    Ricou almost 2 years

    I'm using the Vuetify Autocomplete with remote data, and I would like to to throttle / debounce the API calls (wait 500 ms to call the API when the user is typing text in the autocomplete). How can I do that?

    I saw a Stack OverFlow post about the debounce-search attribute, but it didn't work for me, and I didn't see any Vuetify documentation on this attribute.

  • tony19
    tony19 over 2 years
    @PierrickMartellière That seems unrelated to this question. Can you post a new question with a link to a reproduction of the problem?