当频繁点击提交按钮时,如果没有作相应的限制,就会不断的触发相应的逻辑,造成一定的问题,就像添加数据按钮,如果不作限制,就会被提交多次,因为需要用防抖来作限制,当连续点击按钮时,按钮的点击事件只会触发触发一次,结束连续点击后,再次点击按钮时才会触发按钮的点击事件。
一、防抖代码
src/directive/index.js
export const throttle = {
bind: (el, binding) => {
let throttleTime = binding.value; // 防抖时间
if (!throttleTime) {
// 用户若不设置防抖时间,则默认1s
throttleTime = 1000;
}
let timer;
let disable = false;
el.addEventListener(
"click",
(event) => {
if (timer) {
clearTimeout(timer);
}
if (!disable) {
// 第一次执行(一点击触发当前事件)
disable = true;
} else {
event && event.stopImmediatePropagation();
}
timer = setTimeout(() => {
timer = null;
disable = false;
}, throttleTime);
},
true
);
},
};
二、注册防抖指令
main.js
import { throttle } from "@/directive/index";
Vue.directive("throttle", throttle);
三、页面使用
<el-button
@click="postList()"
type="primary"
v-throttle="2000"
>提交</el-button>
来源: https://blog.csdn.net/weixin_46996561/article/details/129917458