<!-- eslint-disable vue/multi-word-component-names -->
<template>
<div>
<div>
<h2>实现按钮点击时节流函数</h2>
<p>{{ num }}</p>
<h1>定义触发的事件</h1>
<button @click="add">点击触发</button>
</div>
<div class="box">
<h3>{{msg}}</h3>
<button @click="fdd">实现防抖效果</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
// 定义一个节流方法实现函数的节流
// num表示要处理的事件
const num = ref(1)
// 定义一个状态标记位--默认状态下是true节流阀表示开着的
const flag = ref(true)
// 定义throttle方法
const throttle = (fn: () => void, delay: number | undefined) => {
// 进行判断
if (flag.value) {
setTimeout(() => {
// 在定时器中进行外部传入要执行函数的调用
fn()
// 将状态设置为true
flag.value = true
}, delay)
}
// 在定时器执行结束状态时进行标记位的关闭节流阀
flag.value = false
}
// 定义一个处理数据的方法
const eve = () => {
num.value++
}
// 定义一个点击要触发节流的函数方法
const add = () => {
throttle(eve, 1000)
}
// 定义一个防抖的效果存储的值
const msg=ref(2)
// 定义一个防抖的时间
const timer=ref()
// 实现防抖的函数
// eslint-disable-next-line no-undef
const debounce=(fn: TimerHandler,delay: number|undefined)=>{
if(timer.value){
clearTimeout(timer.value)
// 执行定时器中的人物
}
timer.value=setTimeout(fn,delay)
}
// 定义一个处理函数的方法
const ssd=()=>{
msg.value++
}
// 定义一个触发的函数
const fdd=()=>{
debounce(ssd,2000)
}
</script>
<style scoped>
.box{
width: 300px;
height: 300px;
border: 1px solid #000;
}
</style>