1.可以在utils文件夹中新建一个common.js文件
// 防抖
export const Debounce = (fn, t) => {
let delay = t || 500;
let timer;
console.log(fn)
console.log(typeof fn)
return function () {
let args = arguments;
if(timer){
clearTimeout(timer);
}
timer = setTimeout(() => {
timer = null;
fn.apply(this, args);
}, delay);
}
};
// 节流
export const Throttle = (fn, t) => {
let last;
let timer;
let interval = t || 500;
return function () {
let args = arguments;
let now = +new Date();
if (last && now - last < interval) {
clearTimeout(timer);
timer = setTimeout(() => {
last = now;
fn.apply(this, args);
}, interval);
} else {
last = now;
fn.apply(this, args);
}
}
};
2.在需要使用的组件中引入
import { Debounce } from "@/utils/common.js";
3.使用
methods:{
getSearchGoods: Debounce(function () {
},1000),
}