Vue.js - 元素UI - 输入远程搜索去抖动

时间:2017-06-02 17:10:54

标签: vuejs2

我正在使用vue.js 2.3element-ui input remote search组件。 documentation here

我希望能debounce使用lodash远程搜索,但由于cb中的querySearchAsync(queryString, cb)

,我觉得这很棘手

https://jsfiddle.net/1tgqn7o8/

<div id="app">
Fetch suggestion counter : {{counter}}
<el-autocomplete v-model="state4" :fetch-suggestions="querySearchAsync" placeholder="Please input" @select="handleSelect"></el-autocomplete>
</div>

var Main = {
    data() {
      return {
        links: [],
        state4: '',
        timeout:  null,
        counter: 0,
      };
    },
    methods: {
      loadAll() {
        return [
          { "value": "vue", "link": "https://github.com/vuejs/vue" },
          { "value": "element", "link": "https://github.com/ElemeFE/element" },
          { "value": "cooking", "link": "https://github.com/ElemeFE/cooking" },
          { "value": "mint-ui", "link": "https://github.com/ElemeFE/mint-ui" },
          { "value": "vuex", "link": "https://github.com/vuejs/vuex" },
          { "value": "vue-router", "link": "https://github.com/vuejs/vue-router" },
          { "value": "babel", "link": "https://github.com/babel/babel" }
         ];
      },
      querySearchAsync(queryString, cb) {
        this.counter ++;
        var links = this.links;
        var results = queryString ? links.filter(this.createFilter(queryString)) : links;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      },
      createFilter(queryString) {
        return (link) => {
          return (link.value.indexOf(queryString.toLowerCase()) === 0);
        };
      },
      handleSelect(item) {
        console.log(item);
      }
    },
    mounted() {
      this.links = this.loadAll();
    }
  };
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

2 个答案:

答案 0 :(得分:3)

只需将该功能包装为去抖动。

querySearchAsync: _.debounce(function (queryString, cb) {
    this.counter ++;
    var links = this.links;
    var results = queryString ? links.filter(this.createFilter(queryString)) : links;

    clearTimeout(this.timeout);
    this.timeout = setTimeout(() => {
      cb(results);
    }, 3000 * Math.random());
  }, 500),

更新了fiddle

答案 1 :(得分:2)

您可以像这样简单地添加debounce属性:

<el-autocomplete :debounce="500" :fetch-suggestions="querySearchAsync" />

See official documentation

干杯!