在utils里面创建echarts文件夹例如取名为barGraph.js
下图为barGraph.js代码 逻辑不复杂 不做详细介绍
export default class {
/**
* @descripttion:
* @Author:
* @Date: 2023-02-08 15:29:47
* @params: echarts:echarts原型对象 id:DOM的id data:数据结构 colors:图标颜色(渐变处理,数组两个颜色相同为非渐变)
* @调用方法: new RiskTree(this.$echarts , "DOM的id" , [["沙河", 5, 7, 9, 12.5],......] , [['柱形颜色','柱形颜色']])
*/
constructor(echarts, id, data, colors) {
this.echarts = echarts;
let option = this.getOption(data, colors)
var myChart = echarts.init(document.getElementById(id));
myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
}
getOption(data, colors) {
let seriesArr = []
for (let i = 0; i < colors.length; i++) {
seriesArr.push(
{
type: 'bar', barWidth: 5, itemStyle: {
//柱条渐变色
color: new this.echarts.graphic.LinearGradient(
1, 0, 0, 1,
[
{ offset: 0, color: colors[i][0] },
{ offset: 1, color: colors[i][1] }
]
)
},
}
)
}
let option = {
legend: {},
tooltip: {},
grid: {
x: 26,
y: 25,
x2: 5,
y2: 80,
borderWidth: 10
},
dataset: {
source: data
},
xAxis: {
type: 'category',
splitArea: {//背景
show: true,
areaStyle: {
color: ["rgb(5,31,50,0.8)", "rgb(5,22,37,0.8)"]
}
},
axisLine: { //横轴样式
lineStyle: {
color: '#0f5071'
},
},
axisTick: {
show: false,
borderColor: '#051f32'
},
axisLabel: {
textStyle: {
color: "#3f80ae"
}
},
coordinateSystem: 'cartesian2d', xAxisIndex: 1,
},
yAxis: {
//如果要自己定义刻度线可以在这个地方定义
// min: 0,
// max: 20,
// interval: 5,
axisTick: {
show: false,
},
axisLabel: {
show:true,
interval:0,
textStyle: {
color: "#3f80ae"
},
},
splitLine: {
show: true,
lineStyle: {
color: ['#0f5071'],
width: 1,
type: 'solid',
},
},
},
series: seriesArr
};
return option;
}
}
组件中使用
<template>
<div>
<div class="RiskTree" id="RiskTree"></div>
<div class="RiskTree" id="RiskTree1"></div>
</div>
</template>
<script>
import RiskTree from "@/utils/echarts/barGraph.js";
export default {
components: {},
mounted() {
new RiskTree(
this.$echarts,
"RiskTree",
[
["沙河", 5, 7, 9, 12.5],
["东湖", 5, 7, 9, 1.5],
["十里河", 1, 2, 4, 2.5],
],
[
["#fc342e", "#5a2634"],
["#efc022", "#5f5e31"],
["#00ed82", "#045e4c"],
["#b5babf", "#3c5160"],
]
);
new RiskTree(
this.$echarts,
"RiskTree1",
[
["沙河", 1050],
["东湖", 900],
["十里河", 200],
],
// [["#f8964a", "#334175"]]
[["#556fc4", "#556fc4"]]
);
},
data() {
return {};
},
computed: {},
methods: {},
};
</script>
<style scoped>
.RiskTree {
width: 70vw;
height: 200px;
}
</style>