// debounce
<template>
<!-- 生效 -->
<el-input v-model="value" @keyup="handelKeyUp"></el-input>
<!-- 不生效 -->
<el-input v-model="value" @keyup="debounce(handelKeyUp2,300)"></el-input>
</template>
<script setup>
import { ref } from "vue";
let value = ref("");
// 不生效
function handelKeyUp2 (args) {
console.log("请求url", value.value, args);
};
// 这里不生效的原因是:这里的 debounce() 是直接执行了 debounce,并把它的返回值(undefined)传给了 debounce。
// debounce 实际上收到的是 debounce(undefined, 50),返回的是一个函数,但你并没有保存和调用这个返回的防抖函数。
function debounce(fn, delay = 200) {
let timeout = null;
return function (...args) {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(function () {
fn.apply(this, args);
}, delay);
};
}
// 生效 - 应该先生成防抖函数,再调用它,而不是直接执行 debounce()
const handelKeyUp = debounce(function (args) {
console.log("请求url", value.value, args);
}, 300);
// 同理 - 下面防抖函数的调用
debouncedSyncHeaderRowHeight(){
this.debounce(this.syncHeaderRowHeight(), 50) // 这样的写法,函数就不会执行打印
this.debounce(this.syncHeaderRowHeight(), 50)() // 这样的写法,就可以
},
debounce(func, wait) {
let timeout;
return function(...args) {
clearTimeout(timeout);
console.log(1111)
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
}
</script>