vue3项目中使用lodash库防抖节流

1.项目中使用防抖

安装:
npm i --save-dev @types/lodash

使用组件中引入:
import _ from 'lodash'

引入完成后可能会有报错,找到项目中shims-vue.d.ts文件添加就解决报错

declare module "lodash";

防抖

_.debounce(func, [wait=0], [options=]) 函数在延迟几毫秒之后才执行,也就是停止改变几秒后执行

参数:

func (Function): 要防抖动的函数。
[wait=0] (number): 需要延迟的毫秒数。
[options=] (Object): 选项对象。
[options.leading=false] (boolean): 指定在延迟开始前调用。
[options.maxWait] (number): 设置 func 允许被延迟的最大值。
[options.trailing=true] (boolean): 指定在延迟结束后调用。
 

 

   // 点击触发的函数
    const handleLogin = async () => {
      console.log("触发了");
      let { data: res }: any = await doLogin();
      console.log(res);
      proxy.userName = res.data.msg;
    };
    // 按钮请求防抖
    const fangdou = _.debounce(handleLogin, 500, {
      leading: true, // 延长开始后调用
      trailing: false, // 延长结束前调用
    });
    // 节流
    const jieliu = _.throttle(handleLogin, 2000, {
      leading: true, // 延长开始后调用
      trailing: false, // 延长结束前调用
    });

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue使用lodash来实现节流的方法如下: 1. 安装lodash:在项目根目录下打开命令行工具,执行以下命令安装lodash: ``` npm install lodash ``` 2. 导入lodash:在需要使用节流的组件,导入lodash的相关函数: ```javascript import { debounce, throttle } from 'lodash'; ``` 3. 使用节流函数:使用`throttle`函数来实现节流。`throttle`函数会在指定的时间间隔内只执行一次函数,可以用于限制频繁触发的事件,例如滚动、拖拽等。以下是一个使用节流函数的示例: ```javascript export default { data() { return { scrollHandler: null }; }, methods: { handleScroll() { // 处理滚动事件的逻辑 console.log('Scroll event'); } }, mounted() { this.scrollHandler = throttle(this.handleScroll, 200); // 设置节流时间为200ms window.addEventListener('scroll', this.scrollHandler); }, beforeDestroy() { window.removeEventListener('scroll', this.scrollHandler); } } ``` 在上述代码使用`throttle`函数将`handleScroll`方法包装起来,设置节流时间为200ms。在组件的`mounted`生命周期钩子,将节流后的处理函数添加到`scroll`事件监听器,保证在指定时间间隔内只执行一次。 4. 使用函数:使用`debounce`函数来实现。`debounce`函数会在指定的时间间隔后执行函数,如果在这个时间间隔内又触发了同样的函数,则重新计时。以下是一个使用函数的示例: ```javascript export default { data() { return { inputHandler: null, inputValue: '' }; }, methods: { handleInput() { // 处理输入事件的逻辑 console.log('Input event'); } }, mounted() { this.inputHandler = debounce(this.handleInput, 500); // 设置时间为500ms } } ``` 在上述代码使用`debounce`函数将`handleInput`方法包装起来,设置时间为500ms。在组件的`mounted`生命周期钩子,将后的处理函数赋值给`inputHandler`。 在模板,将处理函数绑定到相应的事件上: ```html <input type="text" v-model="inputValue" @input="inputHandler"> ``` 这样,在输入框输入内容时,只有在500ms内没有再次输入才会触发后的处理函数。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值