vue3中如何使用防抖和节流

1.封装

在src/utils文件夹中新建文件handleDebounce.js,用于封装防抖和节流

// 防抖
export function debounce(fn, delay = 200) {// fn是需要防抖的函数,delay是延迟多少毫秒执行fn
    let timer = null;
    return function () {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}

// 节流
export function throttle(fn, delay = 100) {
    let timer = null;
    return function () {
        if (timer) return;
        timer = setTimeout(() => {
            fn.apply(fn, arguments);
            timer = null;
        }, delay)
    }
}

2.引入使用

<el-button @click="clickEvent">防抖</el-button>
<el-button @click="clickEvent2">节流</el-button>


import { debounce,throttle } from "@/utils/handleDebounce";

const clickEvent = debounce(
  () => {
    console.log("防抖");
  }, 800);

const clickEvent2 = throttle(
  () => {
    console.log("节流");
  }, 800);

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue2,可以使用Lodash库提供的`debounce`(防抖)和`throttle`(节流)方法来实现防抖节流。 1. 防抖 防抖是指在一定时间内,如果事件被触发多次,只执行一次函数。例如,当用户输入关键词进行搜索时,我们希望用户输入完成后再进行搜索,而不是用户每输一个字就进行一次搜索。 使用Lodash库的`debounce`方法可以实现防抖。该方法接受两个参数,第一个参数是要执行的函数,第二个参数是防抖时间,即在多少毫秒内事件被触发多次只执行一次函数。 示例代码: ``` <template> <div> <input type="text" v-model="keyword" @input="debounceSearch" /> </div> </template> <script> import { debounce } from 'lodash'; export default { data() { return { keyword: '', }; }, methods: { debounceSearch: debounce(function() { console.log('搜索关键词:', this.keyword); }, 500), }, }; </script> ``` 2. 节流 节流是指在一定时间内,事件只会被触发一次。例如,当我们在滚动页面时,如果每滚动一点页面就触发一次函数,那么可能会导致页面卡顿。此时我们可以使用节流来控制事件的触发次数,让函数在一定时间内只执行一次。 使用Lodash库的`throttle`方法可以实现节流。该方法接受两个参数,第一个参数是要执行的函数,第二个参数是节流时间,即在多少毫秒内事件只执行一次函数。 示例代码: ``` <template> <div> <p>滚动次数:{{ count }}</p> <div style="height: 200px; overflow: auto" @scroll="throttleScroll"> <div style="height: 1000px"></div> </div> </div> </template> <script> import { throttle } from 'lodash'; export default { data() { return { count: 0, }; }, methods: { throttleScroll: throttle(function() { this.count++; }, 500), }, }; </script> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值