vue按钮实现防抖
Vue 按钮防抖实现方法
防抖(Debounce)是一种限制函数频繁调用的技术,确保函数在指定时间内只执行一次。以下是几种在 Vue 中实现按钮防抖的方法:
使用 Lodash 的 debounce 方法
安装 Lodash 并导入 debounce 函数:
npm install lodash
在 Vue 组件中使用:
import { debounce } from 'lodash';
export default {
methods: {
handleClick: debounce(function() {
console.log('防抖按钮被点击');
// 业务逻辑
}, 300)
}
}
模板中使用:
<button @click="handleClick">防抖按钮</button>
自定义防抖函数实现
创建一个可复用的防抖函数:
function debounce(fn, delay) {
let timer = null;
return function() {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, arguments);
}, delay);
};
}
在 Vue 组件中使用自定义防抖:
export default {
methods: {
handleClick: debounce(function() {
console.log('自定义防抖按钮');
// 业务逻辑
}, 300)
}
}
使用 Vue 指令实现全局防抖
创建全局防抖指令:
Vue.directive('debounce', {
inserted(el, binding) {
let delay = binding.arg || 300;
let timer = null;
el.addEventListener('click', () => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
binding.value();
}, delay);
});
}
});
使用指令:
<button v-debounce:500="handleClick">指令防抖按钮</button>
使用 Composition API 实现
在 Vue 3 中使用 setup 语法:
import { ref } from 'vue';
export default {
setup() {
const handleClick = debounce(() => {
console.log('Composition API 防抖');
}, 300);
return { handleClick };
}
}
注意事项
防抖时间应根据实际需求调整,常见值在 200-500ms 之间
对于表单提交等关键操作,可能需要结合防抖和节流技术
在组件销毁时,应清除防抖定时器以避免内存泄漏







