使用 vue-multiselect 和 lodash 限制 ajax 请求的问题

Issue in throttling ajax requests using vue-multiselect and lodash

我有一个包含 vue-multiselect 的 vue 应用程序,我想通过 ajax 加载多选选项。当用户输入搜索条件时,我正在使用 lodash.throttle 来限制 ajax 请求的触发。但无论我做什么,我都会看到针对我在搜索中键入的每个字符触发了多个请求。我做错了什么?提前致谢。

<template>
<multiselect :options="allLocations.map(p => p.externalId)" 
                :searchable="true" 
                :custom-label="uuid => {const sel = allLocations.filter(s => s.externalId === uuid); return sel.length === 1 ? sel[0].name + ' (' + sel[0].type + ')' : '';}" 
                class="mx-1 my-1" 
                style="width:500px;" 
                v-model="locations"
                :clear-on-select="true" 
                :close-on-select="false" 
                :show-labels="true" 
                placeholder="Pick Locations to filter" 
                :multiple="true" 
                :loading="locationsLoading" 
                :internal-search="false"
                @search-change="findLocations"
                @input="updateLocations" 
                :allowEmpty="true" />
</template>
<script>
import {throttle} from 'lodash'
export default {
name: 'test-throttle-component',
data() {
allLocations: [],
locationsLoading: false,
locations: [],
},
methods: {
findLocations(search) {
      this.$log.debug("Going to find locations for search criteria", search)
      const params = {search: search}
      this.locationsLoading = true
      const self = this
      throttle(() => self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }), 5000)()
    },
updateLocations() {
      const self = this
      this.$store.dispatch('updateSelectedLocations', this.locations)
        .then(() => self.emitRefresh())
    },
}
}
</script>

尝试将 findLocations 方法包装到 throttle 函数:

findLocations: throttle(() => {
      this.$log.debug("Going to find locations for search criteria", search)
      const params = {search: search}
      const self = this
      this.locationsLoading = true
      self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }
}, 5000)

更多信息here

@strelok2010 几乎是正确的,但我认为他忽略了一个事实,即 vue 多选 @search-change 处理程序需要一个接受搜索参数的处理程序,因此代码不会按原样工作。另外我认为,这不会解析为箭头函数内的组件,因此您可能必须使用标准的 JS 函数。这是我认为可行的方法。

findLocations: throttle(function(search) {
      this.$log.debug("Going to find locations for search criteria", search)
      const params = {search: search}
      const self = this
      this.locationsLoading = true
      self.$http.get("locations/ddlist", {params}).then(res => {
        self.allLocations = res.data.items
        self.locationsLoading = false
      }
}, 5000)