可以先在页面中创建一个utils文件,在utils中创建common.js文件使用防抖和节流
防抖的方法:
export const Debounce = function (fn, t) {
let delay = t || 300;
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
}
}
节流的方法:
export const Throttle = function (fn, delay=300) {
let canRun = true; // 通过闭包保存一个标记
return function () {
if (!canRun) return;//在delay时间内,直接返回,不执行fn
canRun = false;
setTimeout(() => {
fn.apply(this, arguments);
canRun = true;//直到执行完fn,也就是delay时间后,打开开关,可以执行下一个fn
}, delay);
};
}
在页面中使用:
import {Debounce,Throttle} from "../utils/common";//引入防抖和节流
//change当前点击事件
//Debounce点击事件绑定防抖的方法
change: Debounce(function (val) {
console.log('防抖了');
}, 3000),