方法一:采用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 秒内最多触发一次,避免滚动时回调函数被频繁调用。 - 这优化了页面滚动的性能,特别是在回调函数较为复杂时。
- 当用户滚动页面时,
示例:结合 leading 和 trailing 选项
假设我们希望在用户第一次触发事件时立即执行函数,并在停止触发 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 事件等。
附:安装和引入问题
问题描述: 新手在使用 vue-lodash 时,可能会遇到安装和引入的问题。
解决步骤:
确保已经正确安装了 vue 和 lodash。
使用 npm 或 yarn 安装 vue-lodash:
npm install --save vue-lodash lodash
或
yarn add vue-lodash lodash
在你的 vue 项目中引入 vue-lodash 和 lodash:
import vue from 'vue'; import vuelodash from 'vue-lodash'; import lodash from 'lodash';
总结
到此这篇关于vue前端实现防抖节流lodash工具库的文章就介绍到这了,更多相关vue前端防抖节流lodash内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论