Home > Net >  I try to use computed to watch navigator.onLine but not work until I refresh the web?
I try to use computed to watch navigator.onLine but not work until I refresh the web?

Time:04-28

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>

CodePudding user response:

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 () {
  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.

CodePudding user response:

Like @Kaocash said browsers api are not reactive, so a watcher won't work

Original answer :


Well, computed property will be updated when data changes on your component, what you need is a watcher :

<template><div>{{isOnline}}</div></template>
...
<script>
...
  data() {
      return {
          isOnline: true
      }
  },
  watch: {
    'navigator.onLine'(val) {
      this.isOnline = val
    },
  },
...
</script>
  • Related