我尝试使用计算的观看Navigator.online,但直到刷新网络才能工作?

发布于 2025-01-24 17:28:18 字数 257 浏览 5 评论 0原文

我尝试使用计算的观看Navigator.online,但直到刷新网络才能工作?

<template><div>{{isOnline}}</div></template>
...
<scirpt>
...
  computed: {
    isOnline() {
      return navigator.onLine;
    },
  },
...
</script>

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一萌ing 2025-01-31 17:28:18

浏览器API不是反应性。因此,每当其价值变化时,Vue都不知道。

要收听Navigator.Online更改,您必须使用浏览器触发的本机事件(请参阅 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)
  }
}

注意:请小心SSR,window在服务器上不存在。

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.

转瞬即逝 2025-01-31 17:28:18

那样

就像@kaocash


说的
您需要的是一个观察者:

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文