问题描述
我使用 vue-chartjs 构建了图表,并使用 axios 从 api 获取数据。目前我有一个 setInterval 每 10 秒加载一次 JSON。我想避免这种情况并仅在 json 更改时加载数据。怎么做?我试图在 this.chart1Data 上设置一个观察者,但没有奏效。
这是代码和框:https://codesandbox.io/s/vue-chartjs-json-data-rnv2v?file=/src/App.vue
解决方法
我认为您正在寻找的是 WebSockets:
var socket = new WebSocket(urlToWebsocketServer);
// callback method is called when connection is established
socket.onopen = function () {
console.log("Connection established");
};
// callback method is called when a new websocket messages is received
socket.onmessage = function (messageEvent) {
console.log(messageEvent.data);
};
// callback method is called when there was an error
socket.onerror = function (errorEvent) {
console.log("Error! Connection was closed");
};
socket.onclose = function (closeEvent) {
console.log('Connection closed --- code: ' + closeEvent.code + ' --- reason: ' + closeEvent.reason);
};
I borrowed this code from wikipedia ;)
编辑:有很多教程。只需使用谷歌。 Maybe this one could be helpful