欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > VUE前端实现防抖节流 Lodash

VUE前端实现防抖节流 Lodash

2025/5/16 16:55:26 来源:https://blog.csdn.net/weixin_45280713/article/details/144723373  浏览:    关键词:VUE前端实现防抖节流 Lodash

方法一:采用Lodash工具库

Lodash 是一个一致性、模块化、高性能的 JavaScript 实用工具库。

(1)采用终端导入Lodash库

$ npm i -g npm
$ npm i --save lodash

(2)应用

示例:搜索框输入防抖

在这个示例中,我们希望用户在输入框中停止输入 500 毫秒后才执行搜索操作,避免频繁请求.

<input type="text" id="search" placeholder="Search..."><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>// 假设这是一个执行搜索操作的函数function performSearch(query) {console.log('Searching for:', query);// 这里可以发送 ajax 请求进行搜索}// 使用 lodash 的 debounce 函数const debouncedSearch = _.debounce(function(event) {performSearch(event.target.value);}, 500);  // 500ms 的防抖时间// 监听输入框的输入事件document.getElementById('search').addEventListener('input', debouncedSearch);
</script>
示例:滚动事件节流

在这个示例中,我们希望当用户滚动页面时,每隔 1 秒才记录一次滚动事件,避免频繁触发回调函数。

<div style="height: 2000px;">Scroll down to see the effect</div>
<!-- 导入 throttle 函数-->
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>// 这是一个处理滚动事件的函数function handleScroll() {console.log('Scroll event detected at:', new Date().toLocaleTimeString());}// 使用 lodash 的 throttle 函数,每隔 1 秒最多触发一次const throttledScroll = _.throttle(handleScroll, 1000);// 监听滚动事件window.addEventListener('scroll', throttledScroll);
</script>
  • 解释
    • 当用户滚动页面时,throttledScroll 函数会在 1 秒内最多触发一次,避免滚动时回调函数被频繁调用。
    • 这优化了页面滚动的性能,特别是在回调函数较为复杂时。
示例:结合 leadingtrailing 选项

假设我们希望在用户第一次触发事件时立即执行函数,并在停止触发 1 秒后再次执行。

<input type="text" id="input-field" placeholder="Type something..."><script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
<script>// 假设这是一个处理输入的函数function handleInput(value) {console.log('Input value processed:', value);}// 使用 debounce 函数,并配置 leading 和 trailing 选项const debouncedInput = _.debounce(function(event) {handleInput(event.target.value);}, 1000, { leading: true, trailing: true });// 监听输入框的输入事件document.getElementById('input-field').addEventListener('input', debouncedInput);
</script>

方法二:自定义防抖、节流函数

(1)在utils文件夹下创建lodash.ts文件,里面定义防抖节流函数


// 防抖函数
export function debounce(fn: Function, delay: number) {let timer: ReturnType<typeof setTimeout> | null = null;return function (this: any, ...args: any[]) {// 清除上一个定时器if (timer) {clearTimeout(timer);}// 设置新的定时器timer = setTimeout(() => {fn.apply(this, args); // 使用apply确保this和参数正确传递}, delay);};
}// 节流函数
export function throttle(fn: Function, delay: number) {let lastTime = 0;return function (this: any, ...args: any[]) {const now = Date.now();// 如果距离上次执行时间已超过指定时间间隔,则执行函数if (now - lastTime >= delay) {lastTime = now;  // 更新上次执行时间fn.apply(this, args);}};
}

(2)应用

防抖
  • 方式一:
<template><div><input v-model="searchText" placeholder="输入搜索内容" /><button @click="handleSubmit">提交</button></div>
</template><script lang="ts" setup>
import { ref } from 'vue';
import { debounce } from '@/utils/debounce';  // 引入自己写的防抖函数// 1. 声明响应式数据
const searchText = ref<string>('');// 2. 防抖函数,延迟1000毫秒执行提交操作
const submitForm = (val: string) => {console.log('提交的搜索值:', val);// 在这里执行提交操作
};// 3. 使用防抖函数包装提交操作
const handleSubmit = debounce(() => {submitForm(searchText.value);  // 使用当前输入的值执行提交操作
}, 1000); // 防抖延迟设置为1000毫秒</script>
  • 方式二:
<template><div><input v-model="searchText" placeholder="输入搜索内容" /><button @click="submitForm(searchText)">提交</button></div>
</template><script lang="ts" setup>
import { ref } from 'vue';
import { debounce } from '@/utils/debounce';  // 引入自己写的防抖函数// 1. 声明响应式数据
const searchText = ref<string>('');// 2. 定义提交表单操作
const submitForm = debounce((val: string) => {console.log('提交的搜索值:', val);// 在这里执行提交操作
}, 1000);  // 防抖延迟设置为1000毫秒</script>
节流
<template><div @scroll="handleScroll" style="height: 300px; overflow-y: scroll;"><!-- 模拟内容,超出容器高度以启用滚动 --><div style="height: 1000px;">滚动内容</div></div>
</template><script lang="ts" setup>
import { throttle } from './debounce';  // 引入节流函数// 1. 定义滚动事件处理函数(节流)
const handleScroll = throttle(() => {console.log('滚动事件触发');// 在这里处理滚动事件,例如加载更多内容
}, 200);  // 每200毫秒只执行一次</script>
<template><div @scroll="handleScroll" style="height: 300px; overflow-y: scroll;"><!-- 模拟内容,超出容器高度以启用滚动 --><div style="height: 1000px;">滚动内容</div></div>
</template><script lang="ts" setup>
import { throttle } from './debounce';  // 引入节流函数// 1. 定义滚动事件处理函数(节流)
const handleScroll = throttle(() => {console.log('滚动事件触发');// 在这里处理滚动事件,例如加载更多内容
}, 200);  // 每200毫秒只执行一次</script>

应用场景

防抖 (debounce):

手抖了。。。多点了好几次,一定时间内只执行一次。(年纪大了手抖)

  • 功能:只有在用户停止触发事件一段时间后,才会执行回调函数。
  • 应用场景:输入框搜索、窗口大小调整(resize)、表单提交等。
节流 (throttle):

好比点了两次下拉刷新列表页面,他不会马上直接执行两次,是在你定义的一定时间间隔前提前,先执行第一次在执行第二次

  • 功能:在指定的时间间隔内,只执行一次函数。如果触发频繁,函数执行会被限制在每个时间间隔内最多执行一次。
  • 应用场景:滚动事件、鼠标移动事件、resize 事件等。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词