Vue.js is failing to update the computed property with navigator.onLine

Looking to utilize Vue.js computed properties to monitor the online status of my application. Here is how I have set up Vue:

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

Here is the markup being used:

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

The expectation was that when connecting or disconnecting from the network, the "onLine" property would toggle between true and false. However, this expected behavior did not occur...

The workaround found was as follows:

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 seems to be a misunderstanding with Vue computed properties. Can someone clarify why it didn't function as anticipated?

Answer №1

I encountered a similar issue, but I was able to resolve it by utilizing Vue.js listening methods http://vuejs.org/guide/reactivity.html#Change-Detection-Caveats

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

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

  window.addEventListener('online', updateConnectionStatus);
  window.addEventListener('offline', updateConnectionStatus);

Answer №2

From what I recall, objects that are observed must be of a primitive or plain nature; "native" objects are unable to be observed directly. The library will simply disregard any attempts to do so.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify whether all of the iframes have finished loading

I am facing an issue with running a function when multiple iframes on the page are loaded using jQuery. The function works fine when there is only one iframe, but as soon as there are more than one, it stops working. Below is the code I am currently using: ...

Updating deeply nested document in Mongoose

Is it possible to change the value of array1.array2.status, according to the schema provided below? const SomeSchema = new mongoose.Schema({ status: Boolean, array1: [{ array2[{ status: boolean }] }] }) ...

Implementing an event listener within a knockoutjs custom directive

I have extensive experience as a knockout user, but I am currently struggling to achieve a specific scenario. For the past few days, I have been trying to create a system within a knockout component that allows observables to translate themselves into diff ...

Enhance the appearance of the activated header - Ionic 3 / Angular 5

On the current page, I want to emphasize the title by underlining it or changing its color - something that clearly indicates to the user which page they are on. Currently, I am utilizing lazy loading for navigating between pages, using modules for each pa ...

I successfully implemented the MongoDB connection in my Node.js application, however, it is unfortunately experiencing issues when tested with JMeter

I attempted to establish a connection between JMeter and MongoDB using JavaScript as the scripting language, but encountered failures. The same code worked successfully in Node JS, however, it fails when implemented in JMeter. var mongo = require('m ...

Enhancing the content of the modal window

Creating a table from an array on the page. When double-clicking on a row in the table, a modal window with input fields should appear, displaying information related to that specific row for editing purposes. However, I'm struggling to figure out how ...

Creating a communication bridge between a Chrome extension and an Angular application on a webpage

There's a chrome extension I've been working on that alters the Dom of webpages. However, I'm dealing with a page built in Angular, which means I need to adjust the scope of the element. How would I go about doing this? ...

Automatically create the web.config file upon executing the command "npm run build"

My Vue app is hosted on IIS. In order to follow the instructions here, I need a custom web.config file in the dist folder. The issue I am facing is that whenever I run "npm run build", the entire dist folder gets deleted, including my web.config file. I th ...

Preventing multiple users from saving the same value for a field using ajax and C#: Best Practices

On my aspx page, I am collecting email addresses from users and making an ajax call like so: function CheckEmailExistence() { $.ajax({ url: "Handler.ashx", contentType: "application/json; charset=utf ...

Even after unsubscribing with mqtt.js, the old listener continues to receive messages

Currently, I am utilizing mqtt.js to receive websocket data from an MQTT server. The subscription process is functioning properly, but the challenge lies in changing the topic dynamically by modifying the websocket configuration. The issue arises when, eve ...

The name you are trying to access from Objects is not defined

Having an issue with a value from an object that is coming up as undefined. It's confusing me, can someone help? Currently fetching data from an endpoint and storing it in state like this: const [manualdata, setManualData] = useState([]); setManualDa ...

I am experiencing an issue with my route where the Passport JWT req.user is unexpectedly undefined

Setting up JWT with my express app has been quite the challenge! Despite getting most of it working, I've encountered a strange issue. My register and login routes are generating valid tokens and authentication works fine in the '/users' rou ...

Attempting to transmit information to MySQL via Ajax and PHP without any observable results

I've encountered an issue when trying to send simple data, such as name, code, and date, to my database. I used JavaScript to gather the data and then sent it to my PHP file using Ajax, but nothing seems to be happening. Can someone please review the ...

Having issues with my CodePen React code and its ability to display my gradient background

I will provide detailed descriptions to help explain my issue. Link to CodePen: https://codepen.io/Yosharu/pen/morErw The problem I am facing is that my background (and some other CSS elements) are not loading properly in my code, resulting in a white bac ...

Express.js in nodejs has encountered an issue known as Error [ERR_HTTP_HEADERS_SENT], which occurs when attempting to set headers after they have already been

An issue with setting headers after they have been sent to the client is causing the Error [ERR_HTTP_HEADERS_SENT]. Despite attempting to handle it with a try-catch block, the error persists. Can someone provide insights on how to resolve this and its unde ...

The Star Rating System fails to update accurately after hiding the Radio Buttons

I followed a tutorial to set up a Star Rating System Everything was working fine on the SHOW PAGE and the INDEX PAGE until I decided to hide the Radio Buttons and use the corresponding labels to submit the value. I encountered an issue where the JavaScrip ...

Ensuring Code Execution Order in NODE.JS

I've encountered an issue with my code that involves parsing a pcap file, storing the data in an array data = [], and then writing it to a JSON file: var fs = require("fs"); var pcapp = require('pcap-parser'); var hex = ""; var data = []; v ...

Manipulate the lines in an HTML map and showcase the distinctions between them

I've been searching through various inquiries on this particular subject, but none have provided me with a satisfactory response. I have created a map where I've set up 4 axes using the following code: function axis() { var bounds = ...

Guide to surrounding each letter in a user-entered string with div elements

I am currently working on a small web app that allows users to input text. The goal is to have the app parse EACH LETTER entered by the user, creating a new div for each character (even spaces). Although the code is functional, I am facing an issue with s ...

What is preventing me from successfully transferring data to a different HTML page?

While I understand that there are numerous questions related to this topic, I believe my situation is unique. I am attempting to transfer form data from one HTML file (test.html) to another HTML file (tut1.html). Essentially, my goal is to extract the dat ...