Solution 1 :

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.

Solution 2 :

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>

Problem :

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>

Comments

Comment posted by nart

where is your navigator? Is it in data option or what?

Comment posted by kissu

Yeah right, the previous syntax was not working with

By esgsw

Leave a Reply

Your email address will not be published. Required fields are marked *