【Vue】在Vue2中使用ApexCharts做实时折线图
记录一下在 Vue2 中使用 ApexCharts 做实时折线图的过程。
安装 ApexCharts
1
npm install --save apexcharts vue-apexcharts
在 main.js 中添加
1
2
3import VueApexCharts from 'vue-apexcharts'
Vue.use(VueApexCharts)在组件中使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141<template>
<div class="hello">
<apexchart
width="500"
type="line"
:options="chartOptions"
:series="series1"
ref="realtimeChart1"
></apexchart>
</div>
</template>
<script>
import VueApexCharts from "vue-apexcharts";
var data1 = [];
var data2 = [];
var lastDate = 0;
function getDayWiseTimeSeries(baseval, count, yrange) {
var i = 0;
while (i < count) {
var x = baseval;
var y =
Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min;
data1.push({
x,
y,
});
data2.push({
x,
y,
});
lastDate = baseval;
baseval += 86400000;
i++;
}
}
getDayWiseTimeSeries(new Date("11 Feb 2017 GMT").getTime(), 10, {
min: 10,
max: 90,
});
function getNewSeries(baseval, yrange) {
var newDate = baseval + 86400000;
lastDate = newDate;
data1.push({
x: newDate,
y: Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min,
});
data2.push({
x: newDate,
y: Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min,
});
}
function resetData() {
data1 = data1.slice(data1.length - 10, data1.length);
data2 = data2.slice(data2.length - 10, data2.length);
}
export default {
name: "PageHome",
components: {
apexchart: VueApexCharts,
},
data() {
return {
series1: [{ data: data1.slice() }],
series2: [{ data: data2.slice() }],
chartOptions: {
chart: {
animations: {
enabled: true,
easing: "linear",
dynamicAnimation: {
speed: 1000,
},
},
toolbar: {
show: false,
},
zoom: {
enabled: false,
},
},
dataLabels: {
enabled: false,
},
stroke: {
curve: "smooth",
},
title: {
text: "Dynamic Updating Chart",
align: "left",
},
markers: {
size: 0,
},
xaxis: {
type: "datetime",
range: 777600000,
},
yaxis: {
max: 100,
},
legend: {
show: false,
},
},
};
},
mounted() {
this.intervals();
},
methods: {
intervals: function () {
var me = this;
window.setInterval(function () {
getNewSeries(lastDate, { min: 10, max: 90 });
me.$refs.realtimeChart1.updateSeries([{ data: data1 }]);
me.$refs.realtimeChart2.updateSeries([{ data: data2 }]);
}, 1000);
// every 60 seconds, we reset the data to prevent memory leaks
window.setInterval(function () {
resetData();
me.$refs.realtimeChart1.updateSeries([{ data: [] }], false, true);
me.$refs.realtimeChart2.updateSeries([{ data: [] }], false, true);
}, 60000);
},
},
};
</script>
<style scoped>
</style>
【Vue】在Vue2中使用ApexCharts做实时折线图