- 在utils文件夹下创建文件throttle.js文件
export function throttle(fun, delayTime) {
var lastTime;
var timer;
var delayTime = delayTime || 200;
return function () {
var args = arguments;
// 记录当前函数的触发的时间
var nowTime = Date.now();
if (lastTime && nowTime - lastTime < delayTime) {
clearTimeout(timer);
timer = setTimeout(function () {
// 记录上一次函数触发的时间
lastTime = nowTime;
// 修正this指向问题
fun.apply(this, args)
}, delayTime)
} else {
lastTime = nowTime;
fun.apply(this, args);
}
}
}
使用
<el-button @click='antiShake'>节流</el-button>
import { throttle } from "@/utils/throttle.js"
antiShake: throttle(function () {
this.print();
}, 2000),
print(){
console.log('节流');
}