A
A
Alexey Tipa2018-04-01 23:03:56
Vue.js
Alexey Tipa, 2018-04-01 23:03:56

Two divs with data loading, how to do it in Vue.js?

Imagine you have two divs, one next to the other.
Each of the divs receives data to display inside itself from a json file.
Two divs - two json files.
The data is shown in such a way that any change in the json file results in an instant change inside the div.
Please help me implement this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-04-02
@KayzerSoze

Vue alone will not be enough - in addition to displaying data on the client, you also need to monitor changes in files on the server. You can try to look towards node.js + websocket.
Solution sketch, server (using ws ):

const fs = require('fs');

let ID = 0;
const clients = {};

new (require('ws').Server)({
  port: 8081,
}).on('connection', ws => {
  const id = ++ID;
  clients[id] = ws;

  ws.on('close', () => {
    delete clients[id];
  });
});

fs.watch('./', (eventType, filename) => {
  if (/\.json$/.test(filename)) {
    fs.readFile(filename, 'utf8', (err, data) => {
      if (!err && data) {
        const info = JSON.stringify({
          filename,
          data: JSON.parse(data),
        });

        Object.values(clients).forEach(n => n.send(info));
      }
    });
  }
});

Customer:
<div id="app">
  <div v-for="(data, name) in files">
    <div>{{ name }}</div>
    <div>{{ data }}</div>
  </div>
</div>

new Vue({
  el: '#app',
  data: {
    socket: null,
    files: {},
  },
  created() {
    this.socket = new WebSocket('ws://localhost:8081');
    this.socket.onmessage = e => {
      const f = JSON.parse(e.data);
      this.$set(this.files, f.filename, f.data);
    };
  },
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question