index.mjs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import { ref, onMounted, watch } from 'vue';
  2. import { isNumber, isUndefined } from '../../utils/types.mjs';
  3. import { isObject } from '@vue/shared';
  4. const useThrottleRender = (loading, throttle = 0) => {
  5. if (throttle === 0)
  6. return loading;
  7. const initVal = isObject(throttle) && Boolean(throttle.initVal);
  8. const throttled = ref(initVal);
  9. let timeoutHandle = null;
  10. const dispatchThrottling = (timer) => {
  11. if (isUndefined(timer)) {
  12. throttled.value = loading.value;
  13. return;
  14. }
  15. if (timeoutHandle) {
  16. clearTimeout(timeoutHandle);
  17. }
  18. timeoutHandle = setTimeout(() => {
  19. throttled.value = loading.value;
  20. }, timer);
  21. };
  22. const dispatcher = (type) => {
  23. if (type === "leading") {
  24. if (isNumber(throttle)) {
  25. dispatchThrottling(throttle);
  26. } else {
  27. dispatchThrottling(throttle.leading);
  28. }
  29. } else {
  30. if (isObject(throttle)) {
  31. dispatchThrottling(throttle.trailing);
  32. } else {
  33. throttled.value = false;
  34. }
  35. }
  36. };
  37. onMounted(() => dispatcher("leading"));
  38. watch(() => loading.value, (val) => {
  39. dispatcher(val ? "leading" : "trailing");
  40. });
  41. return throttled;
  42. };
  43. export { useThrottleRender };
  44. //# sourceMappingURL=index.mjs.map