繁体   English   中英

使用 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 function:

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)

更多信息在这里

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM