防抖的封装和使用

阻止提交事件因为网络不好等原因提交多次,加个防抖就好了;
封装后如下:

//防抖
export const debounce = (fn, delay) => {
	let timer;
	return function() {
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(() => {
			// 没有参数的时候用fn()就够用了
			// 有的函数会有参数,必须用到this指向才能把参数传过去;
			fn.call(this, ...arguments);
		}, delay);
	};
};

调用:

import { debounce } from "@/utils/factory";

// 没有参数的函数加上防抖
const handleSave = debounce(() => {
   addUserGroupListFetch(formState.value).then((res) => {
     if (res.data.code === "0000") {
       message.success("添加成功!");
       setEdit("see", res.data.id);
     }
   });
 }, 200);
    
// 有参数的函数也可以正常使用
const saveParameter = debounce((row, index) => {
 	// ...
}200

以上代码都是使用的vue3;

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐