Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

vue.js - Vuetify : throttle / debounce v-autocomplete

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...