我正在使用vue.js 2.3
和element-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')
答案 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" />
干杯!