vue实现防抖节流
Vue 中实现防抖与节流
防抖(Debounce)和节流(Throttle)是前端开发中常用的性能优化技术,用于控制事件触发的频率。以下是它们在 Vue 中的实现方法。
防抖(Debounce)
防抖的核心是延迟执行,直到事件停止触发后一段时间才执行。
方法一:使用 Lodash 库
安装 Lodash:
npm install lodash
在 Vue 组件中使用:
import { debounce } from 'lodash';
export default {
methods: {
handleInput: debounce(function() {
// 处理逻辑
}, 500),
},
};
方法二:手动实现防抖
export default {
data() {
return {
timeout: null,
};
},
methods: {
handleInput() {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => {
// 处理逻辑
}, 500);
},
},
};
节流(Throttle)
节流的核心是固定时间间隔内只执行一次。
方法一:使用 Lodash 库
import { throttle } from 'lodash';
export default {
methods: {
handleScroll: throttle(function() {
// 处理逻辑
}, 500),
},
};
方法二:手动实现节流
export default {
data() {
return {
lastExecTime: 0,
};
},
methods: {
handleScroll() {
const now = Date.now();
if (now - this.lastExecTime >= 500) {
// 处理逻辑
this.lastExecTime = now;
}
},
},
};
在模板中使用
<template>
<input @input="handleInput" />
<div @scroll="handleScroll">滚动内容</div>
</template>
注意事项
- 防抖适合用于输入框搜索等场景,确保用户停止输入后才触发。
- 节流适合用于滚动事件或频繁触发的 UI 事件,避免过多计算。
- 使用 Lodash 可以简化代码,但手动实现更灵活。
以上方法可以根据实际需求选择,结合 Vue 的生命周期和事件绑定灵活应用。







