vue3.0封装防抖和节流

文章介绍了如何在Vue3.0项目中封装防抖和节流函数,用于优化事件处理,如点击事件。在utils文件夹下创建了throttle.js,分别实现了节流和防抖函数,通过设置定时器来控制函数的执行频率。在页面中,这两个函数被应用到按钮的点击事件上,展示了它们的实际效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue3.0封装防抖和节流

1.节流和防抖

节流
点击事件,在一段事件内连续点击,指定时间内只触发一次

防抖
点击后1秒之后再触发事件相当于setTimeout

在utils文件下创建throttle.js
// 节流
export  const throttle=(fn, time)=> {
    let timer = null
    time = time || 1000
    return function(...args) {
        if (timer) {
            return
        }
        const _this = this
        timer = setTimeout(() => {
            timer = null
        }, time)
        fn.apply(_this, args)
    }
}

// 防抖
export const debounce=(fn, time)=> {
    time = time || 200
    // 定时器
    let timer = null
    return function(...args) {
        const _this = this;
        if (timer) {
            clearTimeout(timer)
        }
        timer = setTimeout(function() {
            timer = null
            fn.apply(_this, args)
        }, time)
    }
}

在页面中使用
<template>
  <div>
    <el-button type="primary" plain @click="btnClick">节流</el-button>
    <el-button type="primary" plain @click="btnClick2">防抖</el-button>
  </div>
</template>

<script setup>
import {throttle,debounce} from '@/utils/throttle'
// 节流
const btnClick=throttle((e) => {
  console.log('节流')
}, 1500)
// 防抖
const btnClick2=debounce((e) => {
  console.log('防抖')
}, 1000)
</script>

<style scoped>
</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值