我在 keyUp 上调用 searchkeyword 函数。我想在快速输入新字母时取消/clearTimeout $emit,这样只有几次 $emit 被调用。 但是控制台在每次搜索关键字调用时都会被调用/反跳。
methods: {
searchKeyword : function() {
var scope = this;
(this.debounce(function(){
scope.$emit("search-keyword", scope.keyword);
console.log("Called");
},350))();
},
debounce: function (func, delay) {
var timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), delay);
}
}
}
最佳答案
你的方法很好,设置超时然后清除它是一种众所周知的去抖动方法。这answer描述它并使用相同的方法。
问题是您在每次调用 searchKeyword
时都会创建一个新的去抖动函数,然后立即执行它。
您需要直接传递 debounced 函数。
const debounce = (fn, delay) => {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(_ => fn.apply(context, args), delay);
};
};
new Vue({
el: '#root',
name: "App",
data: _ => ({ called: 0 }),
methods: {
doSomething: debounce(function() {
this.called += 1;
}, 2000)
},
template: `
<div>
<button v-on:click='doSomething'>Do Something</button>
I've been called {{ called }} times
</div>
`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='root'></div>
另请注意,debounce 不需要是您组件的方法。
关于javascript - 每次都调用 debounce 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55867533/