DEV Community

loading...
Cover image for Painless way to detect if your Vue app is offline 😎

Painless way to detect if your Vue app is offline 😎

wakeupmh profile image Marcos Henrique ・2 min read

Introduction 🎒


To make it easy and practical we use v-offline a npm module to detect offline and online events for your vue app, discarding a need to handle these envents with event listener.

We use a toast to indicates it, for this we will install bootstrap-vue a npm module too, you can see more about in documentation.

Installs

Execute this commands to add into your Vue application:

NPM

 npm i --save v-offline bootstrap-vue

YARN

yarn add v-offline bootstrap-vue

Warning that the internet has fallen

Let's create a component to handle this πŸ˜‰

Where we will implement v-offline, just import it and bind it with whatever method name I find convenient, in my case I used handleConnectivityChange inside Vue methods, returning to us false if is offline and true if is online, finally we'll show a toast with bootstrap-vue to indicates our state.

<template>
    <div  id="app">
        <Offline @detected-condition="handleConnectivityChange">
        </Offline>
    </div>
</template>
<script>
import Vue from 'vue'
import Offline from  'v-offline'
import BootstrapVue from 'boostrap-vue'

Vue.use(BootstrapVue)

export  default {
    components: { Offline },
    mounted () {},
    methods: {
        handleConnectivityChange (status) {
            if (!status) { this.toast('b-toaster-top-full') }
        },
        toast (toaster, append  =  false) {
            this.$bvToast.toast(`VocΓͺ estΓ‘ offline.`, {
                title:  `ConexΓ£o perdida!`,
                toaster: toaster,
                solid:  true,
                appendToast: append
            })
        }
    }
}

</script>

If you don't know much about Vue, I recommend the documentation which is an incredible and well explanatory reference for those just starting out.

Feel free to manipulate these states as you please, for today is just, see you next time, thank you for reading 🍻.

Discussion

pic
Editor guide
Collapse
drewtownchi profile image
Drew Town

I was curious as to how v-offline was working under the hood and it looks like it is using the Window.Navigator object which I had never heard of before. Then it seems to listen to a few events and update the isOnline status based on those events the browser fires.

That was a fun little rabbit hole. Thanks for sharing!

Collapse
wakeupmh profile image
Marcos Henrique Author

I believe that it implements some event listeners along with the observes of vue to do this behind the scenes, thank you for reading, it made my life a lot easier, the navigator is a hand on the wheel for several methods at a glance here If you want know more about πŸ˜€

Collapse
vladislavkarpov profile image
Vlad K.

How to use this module without a component, if say I want just to use this feature in a method or similar and not output it to the frontend?