应用场景:① 需要在series中另外添加某些属性时;
② 当后端给到的数据结构不符合,需要修改时;
一、效果展示
二、实现代码
<template>
<div class="barChart"></div>
</template>
<script>
import { getCostEnergyApi } from "@/api/stat";
export default {
name: "",
data() {
return {
chart: null, // 保存echarts实例
};
},
mounted() {
this.getDetailApi();
setInterval(this.getDetailApi, 300000); // 每隔5分钟自动刷新数据
},
methods: {
// 接口
getDetailApi() {
getCostEnergyApi().then((res) => {
let resultData = res.data;
if (res.code == 0) {
let timeXData = resultData.time;
let legendData = resultData.legend;
let dataYData = resultData.data;
// 接口重要数据传递
this.setChart(timeXData, legendData, dataYData);
}
});
},
setChart(timeXData, legendData, dataYData) {
// let myChart = this.$echarts(this.$el);
if (!this.chart) {
this.chart = this.$echarts(this.$el);
}
this.chart.setOption({
grid: {
top: "20%",
bottom: "15%",
left: 68,
right: 40,
},
tooltip: {
trigger: "axis",
axisPointer: {
type: "shadow",
},
},
legend: {
left: "50%",
top: "10%",
itemWidth: 7,
itemHeight: 7,
textStyle: {
color: "#5CB1C1",
fontSize: 10,
},
},
calculable: true,
xAxis: [
{
type: "category",
name: "(月)",
nameTextStyle: {
color: "#5cb1c1",
fontSize: 10,
},
axisLine: {
symbol: ["none", "arrow"],
symbolSize: [6, 6],
lineStyle: {
color: "#122C49",
},
},
axisLabel: {
interval: 0,
color: "#61B9C8",
showMaxLabel: false,
fontSize: 10,
},
data: timeXData,
},
],
yAxis: [
{
type: "value",
axisLine: {
symbol: ["none", "arrow"],
symbolSize: [6, 6],
lineStyle: {
color: "#122C49",
},
},
axisLabel: {
color: "#61B9C8",
showMaxLabel: false,
fontSize: 10,
},
splitLine: {
show: false,
},
name: "(元)",
nameGap: -10,
nameTextStyle: {
color: "#61B9C8",
fontSize: 9,
align: "right",
padding: [0, 6, 0, 0],
},
},
],
series: (function () {
let colorArr = [
["#fbcbca", "#f682b4"],
["#06befe", "#1019ce"],
];
var series = [];
for (var i = 0; i < dataYData.length; i++) {
var item = {
name: legendData[i],
data: dataYData[i],
type: "bar",
barGap: 0,
barWidth: 18,
barCategoryGap: 10,
itemStyle: {
color: {
type: "linear",
x: 0,
y: 0,
x2: 0,
y2: 1,
colorStops: [
{
offset: 0,
color: colorArr[i][0], // 0% 处的颜色
},
{
offset: 1,
color: colorArr[i][1], // 100% 处的颜色
},
],
global: false, // 缺省为 false
}, //背景渐变色
},
};
series.push(item);
}
return series;
})(),
});
//随着屏幕大小调节图表
window.addEventListener("resize", () => {
this.chart.resize();
});
},
},
};
</script>
<style lang="less" scoped>
.barChart {
height: 100%;
width: 100%;
}
</style>