【问题标题】:Vuetify : throttle / debounce v-autocompleteVuetify:节流/去抖动 v-autocomplete
【发布时间】:2019-11-11 06:20:27
【问题描述】:

我正在对远程数据使用 Vuetify 自动完成功能,并且我想限制/消除 API 调用(当用户在自动完成中键入文本时,等待 500 毫秒以调用 API)。我该怎么做?

我看到了关于 debounce-search 属性的 Stack OverFlow 帖子,但它对我不起作用,而且我没有看到任何关于此属性的 Vuetify 文档。

【问题讨论】:

    标签: vue.js vuetify.js debounce


    【解决方案1】:

    您可以向进行 API 调用的函数添加去抖动功能。可以使用setTimeoutclearTimeout 实现去抖,这样新的呼叫会被延迟并取消任何待处理的呼叫:

    methods: {
      fetchEntriesDebounced() {
        // cancel pending call
        clearTimeout(this._timerId)
    
        // delay new call 500ms
        this._timerId = setTimeout(() => {
          this.fetch()
        }, 500)
      }
    }
    

    这样的方法可以绑定到v-autocompletesearch-input 属性上的watcher

    <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

    【讨论】:

    • @PierrickMartellière 这似乎与这个问题无关。您可以发布一个新问题,并附上问题重现的链接吗?
    【解决方案2】:

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

    <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);
        },
    

    【讨论】:

      猜你喜欢
      • 2015-07-25
      • 2012-07-13
      • 2021-07-09
      • 2018-02-16
      • 2016-05-21
      • 1970-01-01
      • 2021-12-03
      • 2023-02-24
      • 2020-08-28
      相关资源
      最近更新 更多