在vue中使用防抖和节流。
先在utils.js中定义防抖和节流函数。
// 节流
export function throttle(fn, delay) {
let prev = Date.now();
return function() {
let now = Date.now();
if (now - prev >= delay) {
fn.apply(this, arguments);
prev = Date.now();
}
}
}
// 防抖
export function debounce(fn, wait) {
let timeout = null;
return function() {
let _that = this
if (timeout !== null) clearTimeout(timeout);//如果多次触发将上次记录延迟清除掉
timeout = setTimeout(function() {
fn.apply(_that, arguments);
timeout = null;
}, wait);
};
}
在使用页面导入函数
在methods中使用:
methods: {
clickName1: debounce(function(){
console.log('防抖')
}, 1000),
clickName2: throttle(function() {
console.log('节流')
}, 1000)
}