vue中使用防抖和节流

一、防抖

n秒后执行该事件,如果n秒内被重复触发,则重新计时 。

总结:多次点击,最后一次执行。

二、节流

n秒内运行一次,如果n秒内重复触发,只生效一次。

总结:间隔时间内执行一次。

二、使用步骤

1.封装js文件

代码如下(示例):

//封装防抖
const debounce = (fn, delay) => {
    let timer = null;
    return function () {
        let context = this;
        let args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            fn.apply(context, args);
        }, delay);
    };
};

//封装节流
const throttle = (fn, delay) => {
    let flag = true;
    return function () {
        if (!flag) return
        flag = false;
        setTimeout(() => {
            fn.apply(this, arguments)
            flag = true;
        }, delay);
    }
};

export {
    throttle,
    debounce
};

2、组件中使用

代码如下(示例):

<script setup>
import { debounce, throttle } from '../untill/index'
let handleDebounce = () => {
    console.log('防抖执行')
}
let handleThrottle = () => {
    console.log('节流执行')
}
// 执行防抖
let db_debounce = debounce(handleDebounce, 2000)
// 执行节流
let db_throttle = throttle(handleThrottle, 2000)
</script>

<template>
    <button @click="db_debounce">防抖</button>
    <button @click="db_throttle">节流</button>
</template>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猛男敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值