vue + 封装防抖复用方法
防抖函数的作用在于,会延迟触发某个事件(处理函数),在一段(规定)时间内只执行一次。
如果在延迟时间内多次触发了同一个事件(比如规定时间2s,在2s内连续点击同一个按钮触发同一个事件)。防抖函数会取消之前的延迟执行,重新开始计时。
直到延迟时间内没有新的触发,最后才执行一次事件处理函数。
应用场景: 表单验证(输入框校验)、搜索框、按钮,页面滚动
处理方法如下:
utils.js:
// 封装防抖函数
export function debounce(func, wait = 300) {
let timeout;
let hasBeenCalled = false;
const debounced = function(...args) {
const context = this;
if (!hasBeenCalled) {
// 如果是第一次调用,则立即执行并设置标志位
hasBeenCalled = true;
func.apply(context, args);
} else {
// 对于后续调用,清除旧的定时器并设置新的定时器
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(context, args);
// 重置标志位,允许下一次立即执行
hasBeenCalled = false;
}, wait);
}
};
// 提供取消方法以清理定时器
debounced.cancel = () => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
hasBeenCalled = false; // 取消后允许立即重新执行
}
};
return debounced;
}
index.vue:
// html:
<el-button style="float: right" type="primary" @click="handleSearchList()" size="small">查询搜索</el-button>
// js:
import { debounce } from '@/utils/validate' // 导入防抖函数debounce
created(){
// 初始化防抖函数
this.handleSearchList = debounce(this.searchList, 300);
},
methods:{
//搜索
searchList() {
this.listQuery.pageNum = 1
this.getList()
},
}