0

我有一个包含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>
4

2 回答 2

0

尝试将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)

更多信息在这里

于 2020-05-05T14:12:08.287 回答
0

@strelok2010 几乎是正确的,但我认为他忽略了一个事实,即 vue multiselect @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)
于 2020-05-05T15:13:46.143 回答