component
<template>
<button @click="handleClick">
<slot></slot>
</button>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, watch, computed } from 'vue'
import { useThrottleFn } from '/@hooks/useThrottleFn'
export default defineComponent({
name: 'MButton',
emits: {
click: null,
},
setup(props, { attrs, emit }) {
const handleClick = useThrottleFn(
() => {
console.log('click')
},
500,
false
)
return {
handleClick,
}
},
})
</script>
<style scoped>
</style>
useThrottleFn
export function useThrottleFn<T extends Function>(fn: T, delay: number = 500, trailing: boolean = true) {
if (delay <= 0) {
return fn
}
let _exec: number = 0
let _timer: number | null
let _this: any
let _args: any[]
/**
**clear timeout
*/
function clear() {
if (_timer) {
clearTimeout(_timer)
_timer = null
}
}
function timeoutCallback() {
clear()
fn.apply(_this, _args)
}
function wrapper(this: any, ...args: any[]) {
const elapsed = Date.now() - _exec
console.log(elapsed, _exec, delay)
clear()
if (elapsed > delay) {
_exec = Date.now()
console.log(1)
fn.apply(this, args)
}
else
if (trailing) {
console.log(2)
_args = args
_this = this
_timer = window.setTimeout(timeoutCallback, delay)
}
}
return wrapper as Function
}
component当中会提示找不到useThrottleFn的声明
Cannot find module '/@hooks/useThrottleFn' or its corresponding type declarations.
如何书写
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…