【发布时间】:2019-11-11 06:20:27
【问题描述】:
我正在对远程数据使用 Vuetify 自动完成功能,并且我想限制/消除 API 调用(当用户在自动完成中键入文本时,等待 500 毫秒以调用 API)。我该怎么做?
我看到了关于 debounce-search 属性的 Stack OverFlow 帖子,但它对我不起作用,而且我没有看到任何关于此属性的 Vuetify 文档。
【问题讨论】:
标签: vue.js vuetify.js debounce
我正在对远程数据使用 Vuetify 自动完成功能,并且我想限制/消除 API 调用(当用户在自动完成中键入文本时,等待 500 毫秒以调用 API)。我该怎么做?
我看到了关于 debounce-search 属性的 Stack OverFlow 帖子,但它对我不起作用,而且我没有看到任何关于此属性的 Vuetify 文档。
【问题讨论】:
标签: vue.js vuetify.js debounce
您可以向进行 API 调用的函数添加去抖动功能。可以使用setTimeout 和clearTimeout 实现去抖,这样新的呼叫会被延迟并取消任何待处理的呼叫:
methods: {
fetchEntriesDebounced() {
// cancel pending call
clearTimeout(this._timerId)
// delay new call 500ms
this._timerId = setTimeout(() => {
this.fetch()
}, 500)
}
}
这样的方法可以绑定到v-autocomplete 的search-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>
【讨论】:
非常感谢。 有用。 这是我的代码(对地址进行地理编码):
<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);
},
【讨论】: