当前位置: 首页 > news >正文

Vue防抖节流

下面,我们来系统的梳理关于 Vue中的防抖与节流 的基本知识点:


一、核心概念解析

1.1 防抖(Debounce)原理

防抖是一种延迟执行技术,在事件被触发后,等待指定的时间间隔:

  • 若在等待期内事件再次触发,则重新计时
  • 若等待期结束无新触发,则执行函数
// 简单防抖实现
function debounce(func, delay) {let timer;return function(...args) {clearTimeout(timer);timer = setTimeout(() => {func.apply(this, args);}, delay);};
}

应用场景

  • 搜索框输入建议
  • 窗口大小调整
  • 表单验证

1.2 节流(Throttle)原理

节流是一种限制执行频率的技术,确保函数在指定时间间隔内只执行一次:

// 简单节流实现
function throttle(func, limit) {let lastCall = 0;return function(...args) {const now = Date.now();if (now - lastCall >= limit) {func.apply(this, args);lastCall = now;}};
}

应用场景

  • 滚动事件处理
  • 鼠标移动事件
  • 按钮连续点击

1.3 防抖 vs 节流对比

特性防抖节流
执行时机事件停止后执行固定间隔执行
响应速度延迟响应即时响应+后续限制
事件丢失可能丢失中间事件保留最新事件
适用场景输入验证、搜索建议滚动事件、实时定位
用户体验减少不必要操作保持流畅响应

二、Vue 中的实现方式

2.1 方法封装实现

// utils.js
export const debounce = (fn, delay) => {let timer = null;return function(...args) {if (timer) clearTimeout(timer);timer = setTimeout(() => {fn.apply(this, args);}, delay);};
};export const throttle = (fn, limit) => {let lastCall = 0;return function(...args) {const now = Date.now();if (now - lastCall >= limit) {fn.apply(this, args);lastCall = now;}};
};

2.2 组件内使用

<script>
import { debounce, throttle } from '@/utils';export default {methods: {// 防抖搜索search: debounce(function(query) {this.fetchResults(query);}, 300),// 节流滚动处理handleScroll: throttle(function() {this.calculatePosition();}, 100),}
}
</script>

2.3 自定义指令实现

// directives.js
const debounceDirective = {mounted(el, binding) {const [fn, delay = 300] = binding.value;el._debounceHandler = debounce(fn, delay);el.addEventListener('input', el._debounceHandler);},unmounted(el) {el.removeEventListener('input', el._debounceHandler);}
};const throttleDirective = {mounted(el, binding) {const [fn, delay = 100] = binding.value;el._throttleHandler = throttle(fn, delay);el.addEventListener('scroll', el._throttleHandler);},unmounted(el) {el.removeEventListener('scroll', el._throttleHandler);}
};export default {install(app) {app.directive('debounce', debounceDirective);app.directive('throttle', throttleDirective);}
};

三、高级应用模式

3.1 组合式 API 实现

<script setup>
import { ref, onUnmounted } from 'vue';// 可配置的防抖函数
export function useDebounce(fn, delay = 300) {let timer = null;const debouncedFn = (...args) => {clearTimeout(timer);timer = setTimeout(() => {fn(...args);}, delay);};// 取消防抖const cancel = () => {clearTimeout(timer);timer = null;};onUnmounted(cancel);return { debouncedFn, cancel };
}// 在组件中使用
const { debouncedFn: debouncedSearch } = useDebounce(search, 500);
</script>

3.2 请求取消与竞态处理

function debouncedRequest(fn, delay) {let timer = null;let currentController = null;return async function(...args) {// 取消前一个未完成的请求if (currentController) {currentController.abort();}clearTimeout(timer);return new Promise((resolve) => {timer = setTimeout(async () => {try {currentController = new AbortController();const result = await fn(...args, {signal: currentController.signal});resolve(result);} catch (err) {if (err.name !== 'AbortError') {console.error('Request failed', err);}} finally {currentController = null;}}, delay);});};
}

3.3 响应式防抖控制

<script setup>
import { ref, watch } from 'vue';const searchQuery = ref('');
const searchResults = ref([]);// 响应式防抖watch
watch(searchQuery, useDebounce(async (newQuery) => {if (newQuery.length < 2) return;searchResults.value = await fetchResults(newQuery);
}, 500));
</script>

四、性能优化策略

4.1 动态参数调整

function adaptiveDebounce(fn, minDelay = 100, maxDelay = 1000) {let timer = null;let lastExecution = 0;return function(...args) {const now = Date.now();const timeSinceLast = now - lastExecution;// 动态计算延迟时间let delay = minDelay;if (timeSinceLast < 1000) {delay = Math.min(maxDelay, minDelay * 2);} else if (timeSinceLast > 5000) {delay = minDelay;}clearTimeout(timer);timer = setTimeout(() => {lastExecution = Date.now();fn.apply(this, args);}, delay);};
}

4.2 内存泄漏预防

// 在组件卸载时自动取消
export function useSafeDebounce(fn, delay) {const timer = ref(null);const debouncedFn = (...args) => {clearTimeout(timer.value);timer.value = setTimeout(() => {fn(...args);}, delay);};onUnmounted(() => {clearTimeout(timer.value);});return debouncedFn;
}

五、实践

5.1 参数选择参考

场景推荐类型时间间隔说明
搜索建议防抖300-500ms平衡响应与请求次数
表单验证防抖500ms避免实时验证的卡顿
无限滚动节流200ms保持滚动流畅性
窗口大小调整防抖250ms避免频繁重绘
按钮防重复点击节流1000ms防止意外多次提交
鼠标移动事件节流50-100ms保持UI响应流畅

5.2 组合式API最佳实践

<script setup>
import { ref } from 'vue';
import { useDebounce, useThrottle } from '@/composables';// 搜索功能
const searchQuery = ref('');
const { debouncedFn: debouncedSearch } = useDebounce(fetchResults, 400);// 滚动处理
const { throttledFn: throttledScroll } = useThrottle(handleScroll, 150);// 按钮点击
const { throttledFn: throttledSubmit } = useThrottle(submitForm, 1000, {trailing: false // 第一次立即执行
});
</script>

六、实际应用

6.1 搜索框组件

<template><input v-model="query" placeholder="搜索..." @input="handleInput"/>
</template><script setup>
import { ref } from 'vue';
import { useDebounce } from '@/composables';const query = ref('');
const { debouncedFn: debouncedSearch } = useDebounce(search, 400);function handleInput() {debouncedSearch(query.value);
}async function search(q) {if (q.length < 2) return;// 执行搜索API请求
}
</script>

6.2 无限滚动列表

<script setup>
import { onMounted, onUnmounted, ref } from 'vue';
import { useThrottle } from '@/composables';const items = ref([]);
const page = ref(1);
const isLoading = ref(false);// 节流滚动处理
const { throttledFn: throttledScroll } = useThrottle(checkScroll, 200);onMounted(() => {window.addEventListener('scroll', throttledScroll);fetchData();
});onUnmounted(() => {window.removeEventListener('scroll', throttledScroll);
});async function fetchData() {if (isLoading.value) return;isLoading.value = true;try {const newItems = await api.fetchItems(page.value);items.value = [...items.value, ...newItems];page.value++;} finally {isLoading.value = false;}
}function checkScroll() {const scrollTop = document.documentElement.scrollTop;const windowHeight = window.innerHeight;const fullHeight = document.documentElement.scrollHeight;if (scrollTop + windowHeight >= fullHeight - 500) {fetchData();}
}
</script>

七、常见问题与解决方案

7.1 this 上下文丢失

问题:防抖/节流后方法内 this 变为 undefined
解决:使用箭头函数或绑定上下文

// 错误
methods: {search: debounce(function() {console.log(this); // undefined}, 300)
}// 正确
methods: {search: debounce(function() {console.log(this); // Vue实例}.bind(this), 300)
}

7.2 参数传递问题

问题:事件对象传递不正确
解决:确保正确传递参数

<!-- 错误 -->
<input @input="debouncedSearch"><!-- 正确 -->
<input @input="debouncedSearch($event.target.value)">

7.3 响应式数据更新

问题:防抖内访问过时数据
解决:使用 ref 或 reactive

const state = reactive({ count: 0 });// 错误 - 闭包捕获初始值
const debouncedLog = debounce(() => {console.log(state.count); // 总是0
}, 300);// 正确 - 通过引用访问最新值
const debouncedLog = debounce(() => {console.log(state.count); // 最新值
}, 300);

八、测试与调试

8.1 Jest 测试示例

import { debounce } from '@/utils';jest.useFakeTimers();test('debounce function', () => {const mockFn = jest.fn();const debouncedFn = debounce(mockFn, 500);// 快速调用多次debouncedFn();debouncedFn();debouncedFn();// 时间未到不应执行jest.advanceTimersByTime(499);expect(mockFn).not.toBeCalled();// 时间到达执行一次jest.advanceTimersByTime(1);expect(mockFn).toBeCalledTimes(1);
});

8.2 性能监控

const start = performance.now();
debouncedFunction();
const end = performance.now();
console.log(`Execution time: ${end - start}ms`);
http://www.dtcms.com/a/263040.html

相关文章:

  • 最新版 JT/T808 终端模拟器,协议功能验证、平台对接测试、数据交互调试
  • Spring Cloud Bus 和 Spring Cloud Stream
  • HarmonyOS NEXT仓颉开发语言实战案例:外卖App
  • NAT 类型及 P2P 穿透
  • 人工智能和云计算对金融未来的影响
  • Docker 入门教程(九):容器网络与通信机制
  • Qt 前端开发
  • (3)pytest的setup/teardown
  • 文心大模型 4.5 系列开源首发:技术深度解析与应用指南
  • Python 数据分析与可视化 Day 12 - 建模前准备与数据集拆分
  • 【C语言 | 字符串处理】sscanf 用法(星号*、集合%[]等)详细介绍、使用例子源码
  • 嵌入式SoC多线程架构迁移多进程架构开发技巧
  • C++ std::list详解:深入理解双向链表容器
  • uniapp小程序蓝牙打印通用版(集成二维码打印)
  • 深度学习04 卷积神经网络CNN
  • 【Python】 Function
  • 计算整数二进制中1的个数
  • 障碍感知 | 基于3D激光雷达的三维膨胀栅格地图构建(附ROS C++仿真)
  • day47 注意力热图可视化
  • 展示折线图的后端数据连接
  • leetcode427.建立四叉树
  • 利润才是机器视觉企业的的“稳定器”,机器视觉企业的利润 = (规模经济 + 技术差异化 × 场景价值) - 竞争强度
  • ViT与CLIP:图像×文本 多模态读心术揭秘
  • 大数据系统架构实践(三):Hbase集群部署
  • 嘉讯科技:医疗信息化、数字化、智能化三者之间的关系和区别
  • EPLAN 中定制 自己的- A3 图框的详细指南(一)
  • 【机器学习深度学习】适合微调的模型选型指南
  • DAOS集群部署-Docker模式
  • CloudBase AI Toolkit 让我用“嘴”开发出的第一款网页游戏
  • 网络安全运维与攻防演练综合实训室解决方案