Search code examples
javascriptvue.jsreal-time-data

VueJS - Push data into array in V-Bind


I am trying to retrieve data from a list of devices and depending on the number of device, it will graph the data on the chart. The data will also be updated every one second, in other words, I would like to have the chart keep graphing the data in "real-time"

Here is my current code

index.html

<div v-for="data in devices">
    <line-chart :data="[[data.time, data.value]]"></line-chart>
</div>

script (Vue instance)

var displayDataArray = [];

var socket = io.connect();
  socket.on('stream', function (sensorData) {
    app.devices = sensorData.deviceList;
    ProcessData(app.devices);
  });

  function ProcessData(dataObject) {
    var sensorValue;
    for (sensorValue in dataObject) {
      var deviceValue = dataObject[sensorValue];
      displayDataArray.push([deviceValue.timestamp, parseInt(deviceValue.lux)]);
    }
  }

  var app = new Vue({
    el: "#app",
    data: {
      devices: {},
      chartData: displayDataArray
      },
    methods: {
      update() {
        console.log(this.devices);
      }
    }
  });

However, the data is always graphed at one single point. It is not appending onto an array. If I bind :data="chartData" in <line-chart>, it use the data on the second device (if there are two devices is being passed into the devices object) to display on both graph.

Is there a good way to implemented this functionality?

FYI, here is how the object devices looks like

devices's object Thank you for your help!


Solution

  • Will something like the following suit your requirements:

    var socket = io.connect();
    socket.on('stream', function(sensorData) {
        app.devices = sensorData.deviceList;
    });
    
    var app = new Vue({
        el: "#app",
        data: {
            devices: {},
            chartData: {}
        },
        watch: {
            devices (newValue) {
                let chartData = this.chartData
                for(device in newValue) {
                    let deviceValue = newValue[device]
                    if(!chartData[device])
                        chartData[device] = []
                    chartData[device].push([deviceValue.timestamp, parseInt(deviceValue.lux)])
                }
            }
        }
    });
    

    With v-for="device in chartData" ?