VUE前端实现防抖节流 Lodash

118 阅读4分钟

写在前面:

兄弟们,我手里有个长期项目,考虑接私活的可以看看我GitHub!🚀

github.com/ccy-233/cod…

方法一:采用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 @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 事件等。