Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Computed property not updated with navigator.onLine, in Vue.js

I want to use Vue.js computed properties to watch the online status of my app. Basically, I have the following Vue setup:

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

And the following markup:

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

I expected that when I would connect/disconnect my computer from the network, the "onLine" property would change between true and false. However, this doesn't happen...

The only way I could have it change is that one:

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;
});

There must be something that I don't understand about Vue computed properties. Who could tell me why it didn't work the way I expected ?

like image 380
Abrab Avatar asked Dec 18 '22 21:12

Abrab


2 Answers

I had the same problem, but I solved it by using methods to listen that brings Vue.js 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);
like image 133
LordHelloWorld Avatar answered Dec 21 '22 10:12

LordHelloWorld


So if memory serves observed objects must be primitive or plain, "native" objects cannot be directly observed. And the library will ignore attempts to do so.

like image 36
Shaun Hubbard Avatar answered Dec 21 '22 10:12

Shaun Hubbard