Vuetify:油门/反跳v自动完成

Ric*_*cou 2 vue.js debounce vuetify.js

我正在使用带有远程数据的Vuetify自动完成功能,并且我想限制/消除API调用(当用户在自动完成功能中键入文本时,请等待500毫秒以调用API)。我怎样才能做到这一点?

我看到了有关该debounce-search属性的Stack OverFlow帖子,但是对我来说不起作用,并且我也没有看到有关此属性的任何Vuetify文档。

Ric*_*cou 6

非常感谢。有用。这是我的代码(对地址进行地理编码):

<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);
    },
Run Code Online (Sandbox Code Playgroud)


ton*_*y19 5

您可以在执行API调用的函数中添加反跳。可以使用setTimeout和来实现去抖动器clearTimeout,以便延迟新的呼叫并取消任何未决的呼叫:

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

    // delay new call 500ms
    this._timerId = setTimeout(() => {
      this.fetch()
    }, 500)
  }
}
Run Code Online (Sandbox Code Playgroud)

这样的方法可以被结合到观察者search-input的支柱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>
Run Code Online (Sandbox Code Playgroud)

演示