学开发的小伙伴一定遇到过一个问题,就是写点击事件的时候,我们搞开发乖乖的就点击一次,交付给产品使用者的时候,诶!他们拼手速,看谁点的快,这样一来就出现了一个点击事件,短时间内多次被点击的情况,导致事件多次提交,数据紊乱。
这个时候你会用什么方法解决呢,有些小伙伴就会说,按钮加载、蒙版加载、按钮禁用等等方法来解决,今天就来写一个基于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>