Vuetify:节流/去抖动 v-autocomplete [英] Vuetify : throttle / debounce v-autocomplete
问题描述
我将 Vuetify 自动完成与远程数据一起使用,我想限制/消除 API 调用(当用户在自动完成中键入文本时,等待 500 毫秒以调用 API).我该怎么做?
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?
我看到了一篇关于 debounce-search
属性的 Stack OverFlow 帖子,但它对我不起作用,而且我没有看到关于这个属性的任何 Vuetify 文档.
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.
推荐答案
您可以为进行 API 调用的函数添加去抖动功能.可以使用 setTimeout
和 clearTimeout
,这样新的调用就会被延迟并取消任何挂起的调用:
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)
}
}
这样的方法可以绑定到 watcher="https://vuetifyjs.com/en/components/autocompletes#api" rel="noreferrer">search-input
道具 v-autocomplete
:
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>
这篇关于Vuetify:节流/去抖动 v-autocomplete的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!