Uses the Vue composition API, but … doesn't really need to.
Last active
September 16, 2019 15:44
-
-
Save mattattui/49eadddcc28f2b991d731ce6236b85f2 to your computer and use it in GitHub Desktop.
Tracking online/offline state in Vue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<main id="app"> | |
<h1>{{ isOnline ? "Online" : "Offline" }}</h1> | |
</main> | |
</template> | |
<script> | |
import { useNetworkDetection } from "@/services/useNetworkDetection"; | |
export default { | |
setup() { | |
const { isOnline } = useNetworkDetection(); | |
return { | |
isOnline | |
}; | |
} | |
}; | |
</script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Vue from "vue"; | |
import VueCompositionApi from "@vue/composition-api"; | |
import App from "./App.vue"; | |
Vue.use(VueCompositionApi); | |
Vue.config.productionTip = false; | |
new Vue({ | |
render: h => h(App) | |
}).$mount("#app"); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { ref, onBeforeMount, onBeforeUnmount } from "@vue/composition-api"; | |
export function useNetworkDetection() { | |
const isOnline = ref(true); | |
const listener = () => { | |
isOnline.value = navigator.onLine; | |
}; | |
onBeforeMount(() => { | |
window.addEventListener("online", listener); | |
window.addEventListener("offline", listener); | |
listener(); | |
}) | |
onBeforeUnmount(() => { | |
window.removeEventListener("online", listener); | |
window.removeEventListener("offline", listener); | |
}); | |
return { | |
isOnline | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment