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

33 lines
731 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'
import type { TimeoutHandle } from '@element-plus/utils/types'
2020-12-21 20:07:48 +08:00
export default function (loading: Ref<boolean>, throttle = 0) {
2020-12-21 20:07:48 +08:00
if (throttle === 0) return loading
const throttled = ref(false)
let timeoutHandle: TimeoutHandle = 0
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
}