Skip to content

Instantly share code, notes, and snippets.

@mattattui
Last active September 16, 2019 15:44
Show Gist options
  • Save mattattui/49eadddcc28f2b991d731ce6236b85f2 to your computer and use it in GitHub Desktop.
Save mattattui/49eadddcc28f2b991d731ce6236b85f2 to your computer and use it in GitHub Desktop.
Tracking online/offline state in Vue
<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>
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");
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