2020-12-21 20:07:48 +08:00
|
|
|
import { onMounted, ref, watch } from 'vue'
|
2024-11-07 21:31:16 +08:00
|
|
|
import { isNumber, isObject, isUndefined } from '@element-plus/utils'
|
2021-08-24 13:36:48 +08:00
|
|
|
|
2020-12-21 20:07:48 +08:00
|
|
|
import type { Ref } from 'vue'
|
|
|
|
|
2024-11-07 21:31:16 +08:00
|
|
|
export type ThrottleType =
|
|
|
|
| { leading?: number; trailing?: number; initVal?: boolean }
|
|
|
|
| number
|
|
|
|
|
|
|
|
export const useThrottleRender = (
|
|
|
|
loading: Ref<boolean>,
|
|
|
|
throttle: ThrottleType = 0
|
|
|
|
) => {
|
2020-12-21 20:07:48 +08:00
|
|
|
if (throttle === 0) return loading
|
2024-11-07 21:31:16 +08:00
|
|
|
const initVal = isObject(throttle) && Boolean(throttle.initVal)
|
|
|
|
const throttled = ref(initVal)
|
2024-08-05 21:10:14 +08:00
|
|
|
let timeoutHandle: ReturnType<typeof setTimeout> | null = null
|
2020-12-21 20:07:48 +08:00
|
|
|
|
2024-11-07 21:31:16 +08:00
|
|
|
const dispatchThrottling = (timer: number | undefined) => {
|
|
|
|
if (isUndefined(timer)) {
|
|
|
|
throttled.value = loading.value
|
|
|
|
return
|
|
|
|
}
|
2020-12-21 20:07:48 +08:00
|
|
|
if (timeoutHandle) {
|
|
|
|
clearTimeout(timeoutHandle)
|
|
|
|
}
|
2024-08-05 21:10:14 +08:00
|
|
|
timeoutHandle = setTimeout(() => {
|
2020-12-21 20:07:48 +08:00
|
|
|
throttled.value = loading.value
|
2024-11-07 21:31:16 +08:00
|
|
|
}, timer)
|
|
|
|
}
|
|
|
|
|
|
|
|
const dispatcher = (type: 'leading' | 'trailing') => {
|
|
|
|
if (type === 'leading') {
|
|
|
|
if (isNumber(throttle)) {
|
|
|
|
dispatchThrottling(throttle)
|
|
|
|
} else {
|
|
|
|
dispatchThrottling(throttle.leading)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
if (isObject(throttle)) {
|
|
|
|
dispatchThrottling(throttle.trailing)
|
|
|
|
} else {
|
|
|
|
throttled.value = false
|
|
|
|
}
|
|
|
|
}
|
2020-12-21 20:07:48 +08:00
|
|
|
}
|
2024-11-07 21:31:16 +08:00
|
|
|
|
|
|
|
onMounted(() => dispatcher('leading'))
|
2020-12-21 20:07:48 +08:00
|
|
|
|
2021-09-04 19:29:28 +08:00
|
|
|
watch(
|
|
|
|
() => loading.value,
|
|
|
|
(val) => {
|
2024-11-07 21:31:16 +08:00
|
|
|
dispatcher(val ? 'leading' : 'trailing')
|
2020-12-21 20:07:48 +08:00
|
|
|
}
|
2021-09-04 19:29:28 +08:00
|
|
|
)
|
2024-11-07 21:31:16 +08:00
|
|
|
|
2020-12-21 20:07:48 +08:00
|
|
|
return throttled
|
|
|
|
}
|