
1. vue2 如何实现防抖和节流
在 Vue 2 中实现防抖(debounce)和节流(throttle)功能,通常是为了优化用户交互的响应,比如输入框的自动完成、窗口大小调整等场景。
下面分别介绍如何在 Vue 2 中实现这两种功能。
1.1. 防抖(Debounce)
防抖是指在函数被连续调用时,只执行最后一次调用。
这可以减少高频事件触发时不必要的处理,比如搜索建议、窗口调整等。
使用 Lodash
最简单的方法是使用 Lodash 库中的_.debounce 方法。
首先需要安装 Lodash:
npm install lodash
然后在组件中使用它:
import_from'lodash';
export default{
methods:{
handleSearch:_.debounce(function(event){
// 这里是你的处理逻辑
console.log('Search query:',event.target.value);},
300)// 300ms 内没有新的输入才会执行
}
}自定义防抖函数
如果你不想引入整个 Lodash 库,也可以自己写一个简单的防抖函数:
function debounce(func,wait){
let timeout;
return function(...args){
const context=this;
clearTimeout(timeout);
timeout=setTimeout(()=>func.apply(context,args),wait);
};
}
export default{
methods:{
handleSearch:debounce(function(event){
console.log('Search query:',event.target.value);
},300)
}
}1.2. 节流(Throttle)
节流是指在一段时间内最多执行一次函数。这对于防止函数过于频繁地被执行非常有用,例如滚动事件或窗口大小改变事件。
使用 Lodash
Lodash 同样提供了一个_.throttle 方法来帮助我们实现节流:
npm install lodash
然后在组件中使用:
import_from 'lodash';
export default{
methods:{
handleResize:_.throttle(function(){
// 这里是你的处理逻辑
console.log('Window resized');
},1000)// 每隔1秒最多执行一次
},
mounted(){
window.addEventListener('resize',this.handleResize);
},
beforeDestroy(){
window.removeEventListener('resize',this.handleResize);
}
}自定义节流函数
同样地,如果不想依赖 Lodash,你可以自己编写一个简单的节流函数:
function throttle(func,limit){
let inThrottle;
return function(){
const args= arguments;
const context=this;
if(!inThrottle){
func.apply(context,args);
inThrottle=true;
setTimeout(()=> inThrottle=false, limit);
}
};
}
export default{
methods:{
handleResize:throttle(function(){
console.log('Window resized');
},1000)
},
mounted(){
window.addEventListener('resize',this.handleResize);
},
beforeDestroy(){
window.removeEventListener('resize',this.handleResize);
}
}以上就是在 Vue 2 中实现防抖和节流的几种方法。根据你的具体需求选择合适的方式即可。










