From f8fdebffe69d692dbce201ecb050e8eba62edb54 Mon Sep 17 00:00:00 2001 From: xingyu Date: Tue, 31 Oct 2023 10:11:34 +0800 Subject: [PATCH] feat: add useNetwork hooks --- src/hooks/web/useNetwork.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/hooks/web/useNetwork.ts diff --git a/src/hooks/web/useNetwork.ts b/src/hooks/web/useNetwork.ts new file mode 100644 index 00000000..66fa4464 --- /dev/null +++ b/src/hooks/web/useNetwork.ts @@ -0,0 +1,21 @@ +import { ref, onBeforeUnmount } from 'vue' + +const useNetwork = () => { + const online = ref(true) + + const updateNetwork = () => { + online.value = navigator.onLine + } + + window.addEventListener('online', updateNetwork) + window.addEventListener('offline', updateNetwork) + + onBeforeUnmount(() => { + window.removeEventListener('online', updateNetwork) + window.removeEventListener('offline', updateNetwork) + }) + + return { online } +} + +export { useNetwork }