Vue js always run a function to see if user is online or offline
Solution 1:
Create a component OfflineComponent.vue
like this:
<template>
<div>Offline component after 5 seconds!</div>
</template>
<script>
export default {
data() {
return {
showOnce: false,
}
},
mounted() {
this.startInterval()
},
methods: {
startInterval() {
window.setInterval(() => {
if (this.$nuxt.isOffline && !this.showOnce) {
this.runThisFunc()
this.showOnce = true
}
if (this.showOnce) {
clearInterval(window)
}
}, 5000)
},
runThisFunc() {
console.log('OFFLINE!')
},
},
}
</script>
Now import it inside the page you want. I use the main page:
<template>
<div v-if="$nuxt.isOffline">
<offline-component></offline-component>
</div>
<div v-else>You are Online!</div>
</template>
<script>
import OfflineComponent from '~/components/offlineComponent.vue'
export default {
name: 'IndexPage',
components: {
OfflineComponent,
},
}
</script>