Vue前端防抖和节流的实现

学开发的小伙伴一定遇到过一个问题,就是写点击事件的时候,我们搞开发乖乖的就点击一次,交付给产品使用者的时候,诶!他们拼手速,看谁点的快,这样一来就出现了一个点击事件,短时间内多次被点击的情况,导致事件多次提交,数据紊乱。

这个时候你会用什么方法解决呢,有些小伙伴就会说,按钮加载、蒙版加载、按钮禁用等等方法来解决,今天就来写一个基于vue3的防抖和节流的实现。

代码如下:

<template>
    <!-- 事件防抖 -->
    <div class="main">

        <div class="top">
            <button @click="afertClick">防抖</button>
            <p v-show="timer > 0">{{ timer }}</p>
            <p>{{ count }}</p>
        </div>

        <div class="top">
            <button @click="fixedClick">节流</button>
            <p>{{ count2 }}</p>
        </div>

    </div>
</template>

<script lang="ts" setup>
import {ref} from "vue"

let count = ref(0)
let timeout = ref()
let timer = ref(0)   //  读秒时间

const afertClick = () => {  //  防抖,取最后一个值
    cleanLoadingTimeOut()   //  清除还未能执行的定时器
    timeout.value = setTimeout(() => {
        timer.value = 3
        let interval = setInterval(() => {
            timer.value--
            if (timer.value == 0) {
                clearInterval(interval)
                count.value++
                /**
                 * 逻辑处理
                 */
            }
        }, 1000)
    }, 300) //  请求事件频率高于300毫秒则会在方法被执行之前

}
const cleanLoadingTimeOut = () => { //  清除定时器
    clearTimeout(timeout.value)
}


let count2 = ref(0)
let whetherClick = ref(true)

const fixedClick = () => {  //  节流的实现,固定时间内无法重复调用
    if (whetherClick.value) {
        whetherClick.value = false
        setTimeout(() => {
            whetherClick.value = true
            count2.value++
        }, 1000)
    }
}
</script>

<style lang="scss" scoped>
.main {
    width: 100vw;
    height: 100vh;

    .top {
        width: 20vw;
        height: 20vh;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
        border: 1px solid #000;
    }
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值