element-plus/packages/hooks/use-throttle-render/index.ts

32 lines
665 B
TypeScript
Raw Normal View History

2020-12-21 20:07:48 +08:00
import { onMounted, ref, watch } from 'vue'
2020-12-21 20:07:48 +08:00
import type { Ref } from 'vue'
export const useThrottleRender = (loading: Ref<boolean>, throttle = 0) => {
2020-12-21 20:07:48 +08:00
if (throttle === 0) return loading
const throttled = ref(false)
let timeoutHandle = 0
2020-12-21 20:07:48 +08:00
const dispatchThrottling = () => {
if (timeoutHandle) {
clearTimeout(timeoutHandle)
}
timeoutHandle = window.setTimeout(() => {
throttled.value = loading.value
}, throttle)
}
onMounted(dispatchThrottling)
watch(
() => loading.value,
(val) => {
if (val) {
dispatchThrottling()
} else {
throttled.value = val
}
2020-12-21 20:07:48 +08:00
}
)
2020-12-21 20:07:48 +08:00
return throttled
}