useNetWork.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import type { Ref } from 'vue';
  2. import { ref, watch } from 'vue';
  3. import { tryOnMounted, tryOnUnmounted } from '/@/utils/helper/vueHelper';
  4. import { isBoolean } from '/@/utils/is';
  5. const ON_LINE = 'online';
  6. const OFF_LINE = 'offline';
  7. export function useNetWork({
  8. onLineFn,
  9. offLineFn,
  10. }: {
  11. onLineFn?: () => void;
  12. offLineFn?: () => void;
  13. }) {
  14. const onLineRef = ref(navigator.onLine);
  15. // Disconnect time
  16. const offlineAt: Ref<number | undefined> = ref(undefined);
  17. watch(
  18. () => onLineRef.value,
  19. (onLine, oldValue): void => {
  20. if (isBoolean(oldValue) && !oldValue && onLine) {
  21. onLineFn && onLineFn();
  22. } else if (isBoolean(onLine) && !onLine && oldValue) {
  23. // Network to no network
  24. offlineAt.value = Date.now();
  25. offLineFn && offLineFn();
  26. }
  27. },
  28. {
  29. immediate: false,
  30. }
  31. );
  32. const handler = (e: Event) => {
  33. const { type } = e;
  34. onLineRef.value = type === ON_LINE;
  35. };
  36. tryOnMounted(() => {
  37. window.addEventListener(ON_LINE, handler);
  38. window.addEventListener(OFF_LINE, handler);
  39. });
  40. tryOnUnmounted(() => {
  41. window.removeEventListener(ON_LINE, handler);
  42. window.removeEventListener(OFF_LINE, handler);
  43. });
  44. return {
  45. onLineRef,
  46. };
  47. }