I try to use computed to watch navigator.onLine but not work until I refresh the web?
<template><div>{{isOnline}}</div></template>
...
<scirpt>
...
computed: {
isOnline() {
return navigator.onLine;
},
},
...
</script>
Browsers api are not reactive. So whenever their value changes, Vue doesn't know about it.
To listen to navigator.onLine
changes, you have to use a native event fired by the browser (see docs):
data () {
return {
online: false,
}
},
methods: {
onOffline () { this.online = false },
onOnline () { this.online = true },
created() {
window.addEventListener('offline', this.onOffline)
window.addEventListener('online', this.onOnline)
},
destroyed() {
window.removeEventListener('offline', this.onOffline)
window.removeEventListener('online', this.onOnline)
}
}
Note: be careful with SSR, window
doesn't exist on server.