vue实现防抖节流
Vue 中实现防抖(Debounce)
防抖的核心是延迟执行函数,在连续触发时取消前一次的调用,只执行最后一次。适用于输入框搜索、窗口大小调整等场景。
方法1:使用 Lodash 的 _.debounce
安装 Lodash 并导入 debounce 方法:
npm install lodash
在 Vue 组件中使用:
import { debounce } from 'lodash';
export default {
methods: {
handleInput: debounce(function(event) {
console.log('防抖处理:', event.target.value);
}, 500)
}
}
方法2:手动实现防抖 通过 setTimeout 和 clearTimeout 实现:
export default {
data() {
return {
timeout: null
};
},
methods: {
handleInput(event) {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
console.log('防抖处理:', event.target.value);
}, 500);
}
}
}
Vue 中实现节流(Throttle)
节流的核心是限制函数执行频率,在指定时间内只执行一次。适用于滚动事件、频繁点击按钮等场景。
方法1:使用 Lodash 的 _.throttle
import { throttle } from 'lodash';
export default {
methods: {
handleScroll: throttle(function() {
console.log('节流处理滚动事件');
}, 1000)
}
}
方法2:手动实现节流 通过时间戳判断是否执行:
export default {
data() {
return {
lastExecTime: 0
};
},
methods: {
handleClick() {
const now = Date.now();
if (now - this.lastExecTime >= 1000) {
console.log('节流处理点击');
this.lastExecTime = now;
}
}
}
}
在模板中的直接使用
通过指令或事件绑定直接调用防抖/节流方法:
<template>
<input @input="handleInput" />
<button @click="handleClick">提交</button>
</template>
注意事项
- 组件销毁时清除定时器:避免内存泄漏,在
beforeDestroy生命周期中清除未执行的定时器。 - Vue 3 的 Composition API:可以通过
ref和onUnmounted实现更简洁的逻辑。 - 性能权衡:防抖的延迟时间和节流的间隔需根据实际场景调整。







