在Vue中,防抖和节流可以通过多种方式实现,包括装饰器、指令和常规的函数调用。以下是实现防抖和节流的示例代码:
防抖(Debounce)
装饰器
function debounce(delay, callback) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
callback.apply(this, args);
}, delay);
};
}
// 使用
class MyComponent extends Vue {
@debounce(500)
onInputChange(event) {
console.log(event.target.value);
}
}
指令
Vue.directive('debounce', {
bind(el, binding, vnode) {
let timeoutId;
el.addEventListener('input', (e) => {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
binding.value(e);
}, 500);
});
}
});
// 使用
new Vue({
el: '#app',
methods: {
handleInput: debounce(500, function(event) {
console.log(event.target.value);
})
}
});
节流(Throttle)
装饰器
function throttle(delay, callback) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
callback.apply(this, args);
};
}
// 使用
class MyComponent extends Vue {
@throttle(1000)
onScroll() {
console.log(window.scrollY);
}
}
指令
Vue.directive('throttle', {
bind(el, binding, vnode) {
let lastCall = 0;
el.addEventListener('scroll', () => {
const now = new Date().getTime();
if (now - lastCall < 1000) {
return;
}
lastCall = now;
binding.value();
});
}
});
// 使用
new Vue({
el: '#app',
methods: {
handleScroll: throttle(1000, function() {
console.log(window.scrollY);
})
}
});
通用方法
function debounce(fn, delay) {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
function throttle(fn, delay) {
let lastCall = 0;
return function(...args) {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
fn.apply(this, args);
};
}
// 使用
const myDebouncedFunction = debounce(function() {
console.log('Debounced!');
}, 1000);
const myThrottledFunction = throttle(function() {
console.log('Throttled!');
}, 2000);
// 在事件监听器中使用
window.addEventListener('resize', myT