Echarts 图表中动态添加单位


现在有一个需求是:前端根据用户勾选的状态参数绘制多条曲线。

实现思路:

  1. 前端获取到用户勾选的状态参数。
  2. 将状态参数列表发给后端。
  3. 后端将状态参数的数据发给前端。
  4. 前端根据后端发送的参数,分别构建 legend,X 轴,Y 轴数据,并生成图表需要的 option,更新图表。
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
// 根据参数名获取对应的单位
getUnit(key) {
let unit = "";
switch (key) {
case "回风温度":
unit = "℃";
break;
case "回风湿度":
unit = "%";
break;
}
return unit;
},
// 发起请求,更新图表
requestData() {
// 构造 Post 请求参数
const data = {
start: timeToTamp(this.rangeDate[0]),
end: timeToTamp(this.rangeDate[1]),
ids: this.checkedStatus
};
// 向后端请求状态参数数据
chart(getToken("id"), data)
.then(res => {
try {
let that = this; // !!! 注意,此处需要保存 this,在 63 行代码处会用到
// 构造 X 轴数据
let xAxis = [];
for (let i = 0; i < res.timestamp.length; i++) {
xAxis.push(tampToTime(res.timestamp[i]));
}
// 构造 legend 数据
let legend = [];
// 构造 Y 轴数据
let YAxis = [];
for (let key in res.data) {
legend.push(webidToName[key]);
let temp = {};
temp.name = webidToName[key];
temp.type = "line";
temp.unit = res.unit[key];
temp.data = res.data[key];
YAxis.push(temp);
}
// 更新图表
let option = {
legend: {
data: legend
},
xAxis: {
data: xAxis
},
// 鼠标悬浮提示框
tooltip: {
trigger: "axis", // 触发
// 轴指针
axisPointer: {
// 鼠标样式
animation: true,
// 竖线条样式
lineStyle: {
width: 2, // 宽度
opacity: 0.8
}
},
formatter: function(params) {
var relVal = params[0].name;
for (var i = 0, l = params.length; i < l; i++) {
relVal +=
"<br/>" +
params[i].marker +
" " +
params[i].seriesName +
" : " +
params[i].value +
" " +
that.getUnit(params[i].seriesName);
}
return relVal;
}
},
series: YAxis
};
this.chart.setOption(option);
} catch (e) {
console.log(e);
}
})
.catch(err => {
Message({
message: err.response.data.message,
type: "error",
duration: 5 * 1000
});
});
}

参考文档: Echarts 折线图数值后添加单位 提供了根据曲线名查找对应的单位思路。 Echarts 的 tooltip 中动态单位设置(使用 formatter 函数加工) 提供了保存 this 的思路。