1、封装柱状图组件(props:X轴数据、Y轴数据、图标名称)
2、在引用的vue文件中,引入并初始化数据。
chartBar.vue文件
<!-- 柱状图 -->
<template>
<div>
<div :id="echartsId" :class="echartClass"></div>
</div>
</template>
<script>
export default {
components: {},
props: {
echartsId: {
typeo: String, //需要加载的echarts的id
default: ''
},
echartClass:{
typeo: String, //需要加载的echarts的class
default: ''
},
dataValue: {
type: Object, // 需要加载的对象
default: ''
}
},
data() {
return {}
},
mounted(){
this.drawLine()
},
methods:{
drawLine(){
let colorArr = [//两组柱状图的样式
['rgba(0, 226, 255, 0.8)','rgba(0, 99, 191, 0.3)'],
['rgba(239, 197, 3, 0.8)','rgba(211, 197, 132, 0.3)'],
]
this.$nextTick(() => {
let series = []
this.dataValue.value.forEach((item,index)=>{
series.push({
name: item.dataBarName,
type: 'bar',
data: item.dataBar,
barMaxWidth:'40',
itemStyle:{
normal: {
color:new this.$echarts.graphic.LinearGradient(0,0,0,1,[{
offset:0,
color: colorArr[index][0]
},{
offset:1,
color: colorArr[index][1]
}])
},
},
})
})
let barChart = this.$echarts.init(document.getElementById(this.echartsId));
barChart.setOption({
title: {
text: this.dataValue.titleName,//title
textStyle:{
color:"#fff"
}
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
legend: {
textStyle: {
color:'#fff',
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
toolbox: {
feature: {
saveAsImage: {}//允许下载图表
}
},
xAxis: {
type: 'category',
data: this.dataValue.xAxis,//xAxis:X轴数据
axisLabel:{
show:true,
// interval:0,
// rotate:40 ,
textStyle:{
color:"#fff"
}
},
},
yAxis: {
type: 'value',
boundaryGap: [0, 0.01],
axisLabel:{
show:true,
textStyle:{
color:"#fff"
}
},
},
series: series
});
window.addEventListener('resize',function(){//添加此部分,可以使图表随着可视区域进行缩放
barChart.resize()
})
})
}
}
}
</script>
<style scoped lang="scss">
</style>
home.vue文件
此文件引用chartBar.vue文件
注意:接收echart图的div必须设置具体的宽高,否则,图表显示异常
<template>
<div>
<p class="title">各区域入侵面积</p>
<echartBar :echartsId="echartsId" :echartClass="echartClass" :key="'bar'+keyValue" :dataValue="all_ruqinAreaValue"></echartBar>
</div>
</template>
<script>
import echartBar from '../echarts/echartBar.vue'//根据自己的真实路径引用
export default {
components: {echartBar},
data() {
keyValue:1,
all_ruqinAreaValue:{
titleName:'',
xAxis:['北京', '上海', '天津', '四川', '甘肃'],
value:[
{
dataBarName: 'value1',
type: 'bar',
dataBar: [18203, 23489, 29034, 104970, 131744],
},{
dataBarName: 'value2',
type: 'bar',
dataBar: [12003, 20489, 21034, 11970, 17044],
}
]
},
echartsId:'echartsId',
echartClass:'echartClass'
},
watch: {
$route:{
handler(val,oldval){
if(val.path == "/home" ){
this.keyValue++
}
},
// 深度观察监听
deep: true
}
},
method:{
}
}
</script>