Vue.js - Element UI - Input remote search debounce

Viewed 5236

I'm using vue.js 2.3 and element-ui input remote search component. documentation here

I would like to be able to debounce using lodash the remote search, but I find it tricky because of the cb in 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 Answers

You can simply add the debounce atttribute like this:

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

See official documentation

Cheers!

Related