Vue.js 中的计算属性未使用 navigator.onLine 更新

2024-01-23

我想使用 Vue.js 计算属性来查看我的应用程序的在线状态。 基本上,我有以下 Vue 设置:

new Vue({
    el: '#app',
    computed: {
        onLine: function (){
            return navigator.onLine;
        }
    }
})

以及以下标记:

<div id="app">
    <div>{{ onLine }}</div>
</div>

我预计当我将计算机与网络连接/断开时,“onLine”属性将在 true 和 false 之间变化。然而,这并没有发生......

我可以改变它的唯一方法是:

var app = new Vue({
    el: '#app',
    data: {
        onLine: navigator.onLine // initial status
    }
})

window.addEventListener('online',  function(){
    app.onLine = true;
});

window.addEventListener('offline',  function(){
    app.onLine = false;
});

Vue 计算属性肯定有一些我不明白的地方。谁能告诉我为什么它没有按我预期的方式工作?


我遇到了同样的问题,但我通过使用 Vue.js 的监听方法解决了这个问题http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats

var app = new Vue({
    el: '#app',
    data: {
      onLine: navigator.onLine // initial status
    }
  });

  function updateConnectionStatus() {
    app.$set('onLine', navigator.onLine); // this method
  }

  window.addEventListener('online', updateConnectionStatus);
  window.addEventListener('offline', updateConnectionStatus);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Vue.js 中的计算属性未使用 navigator.onLine 更新 的相关文章

随机推荐