使用Websocket或Socket.io的Vue.js实时图表



我的项目使用vue.js。我也使用websocket来获取我的数据。每一秒都会有数据。我需要在我的项目中使用实时图表。但是我找不到任何图表来解决我的问题。例如,我使用apexchart,但当新数据出现时,它不会刷新图表中的数据。

我的websocket数据类似:

{
"topic": "2",
"message": "data"
}

我的数据库数据如下:

{
"id": "1",
"deviceName": "refrigerator",
"deviceType": "lineChart",
"topic": "1",
"message": "",
},
{
"id": "8",
"deviceName": "refrigerator",
"deviceType": "lineChart",
"topic": "1",
"message": "",
},

我用这个代码从数据库中获取数据。我检查一下我的题目,是不是一样。如果相同,我将websocket消息放在json数据中,以便在屏幕上看到:

let bufferMessage = [];
bufferMessage = jsonFromDatabase;
socket.on("message", (topic, message) => {
bufferMessage.forEach(element => {
if (element.topic == topic) {
element.message = message.toString();
}
});
});

我的代码是:

<div id="chart">
<apexchart type="line" height="350" :options="chartOptions" :series="$store.state.bufferMessage[index].message"></apexchart>
</div>
<script>
import Vue from "vue";
import ApexCharts from "apexcharts";
import VueApexCharts from "vue-apexcharts";
Vue.component("apexchart", VueApexCharts);

export default {
components: {
apexchart: VueApexCharts,
},
data() {
return {
series: [
{
name: "Desktops",
data: [],
},
],
chartOptions: {
chart: {
height: 350,
type: "line",
zoom: {
enabled: false,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: "straight",
},
title: {
text: "Product Trends by Month",
align: "left",
},
grid: {
row: {
colors: ["#f3f3f3", "transparent"],
opacity: 0.5,
},
},
xaxis: {
categories: [],
},
},
}
</script>

但是这个代码中没有任何错误。我只想把这个图表转换成我的websocket数据的实时图表。

除非OP在代码中显示了更新数据的部分,否则我只能提供关于更新数据的官方apexcharts文档的参考:

import VueApexCharts from 'vue-apexcharts'
export default {
name: 'Vue Chart',
data: function () {
return {
chartOptions: {
chart: {
id: 'vuechart-example',
},
xaxis: {
categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998],
},
},
series: [{
name: 'Vue Chart',
data: [30, 40, 45, 50, 49, 60, 70, 81]
}]
}
},
methods: {
updateChart() {
const max = 90;
const min = 20;
const newData = this.series[0].data.map(() => {
return Math.floor(Math.random() * (max - min + 1)) + min
})
// In the same way, update the series option
this.series = [{
data: newData
}]
}
}
}

正如您在上面的例子中看到的,只需更改道具,我们就可以触发ApexCharts的更新事件。(来自文档(

沙盒示例https://codesandbox.io/s/50z5wrmp6k

最新更新