为了在一个页面调用多个柱形图,那么回了柱形图,其他的图形封装成组件是不是可以举一反三呢? 我们选择封装组件的形式,方便随调随取,数据分离,互不影响。话不多说,开弄。

一、组件:(@/components/custom/barCharts.vue)

<template>
<div class="echarts">
<!-- 柱形图组件 -->
<div :id="id" :echartObj="echartObj" :style="{width: width, height: height}"></div>
</div>
</template>

<script>
import Echarts from 'echarts'
export default {
data() {
return{
myChart: {}
}
},
props: {
id: {
type: String,
default: "barChart"
},

echartObj: {
type: Object,
default: {}
},

width: {
type: String,
default: "100%"
},

height: {
type: String,
default: "300px"
}
},
created() {
this.$nextTick(()=> {
this.loadEchart()
})
},
mounted(){
let _this = this;
window.onresize = function() {
_this.myChart.resize()
}
},
methods: {
loadEchart() {
this.myChart = Echarts.init(document.getElementById(this.id));
this.myChart.setOption({
title: {
text: this.echartObj.title.text
},
grid: this.echartObj.grid,
tooltip: {},
xAxis: {
type: "category",
name: this.echartObj.xAxis.name,
nameTextStyle: this.echartObj.xAxis.nameTextStyle,
data: this.echartObj.xAxis.data,
axisLine: this.echartObj.xAxis.axisLine,
},
yAxis: {
type: "value",
name: this.echartObj.yAxis.name,
nameTextStyle: this.echartObj.yAxis.nameTextStyle,
axisLine: this.echartObj.yAxis.axisLine,
splitLine: {
show: false //隐藏网格线
}
},
series: this.echartObj.series
})
}
}
}
</script>

说明:

这里面要把id换成变量,因为html中一个id是独享的,不像class那样可以设置多个。

对于柱形图组件的样式,需要动态设置成宽度和高度,当然我这里面是默认成width: 100%;height: 300px;这个你们完全可以自己修改,或者在调用时候传参。

二、调用:healthMonth.vue

首先引入,并注册组件

import BarCharts from "../../../components/custom/barCharts";
components: { 
BarCharts,
}

template中调用:

<!-- 以下两种调用方式无论大写还是小写都是对的 -->

<!-- <bar-charts id="securityChart" :echartObj="echartObj1" width="100%" height="400px"></bar-charts> -->

<BarCharts id="securityChart" :echartObj="echartObj1"></BarCharts>

这里id已经作为一个参数了,方便渲染时候不冲突。

最后一步,安装组件中绑定图形数据的结构传参:

echartObj1: {
title: {
// text: '安全'
},
tooltip: {},
legend: {
data: ['高危', '危险', '低危', '安全']
},
grid: {
right: '70px',
left: '10px',
bottom: '20px',
containLabel:true //自适应
},
xAxis: {
data: ['1月', '2月', '3月', '4月', '5月', '6月','7月', '8月', '9月', '10月', '11月', '12月'],
axisLine:{
lineStyle:{
color:'#fff',
width:1
}
},
name: `${new Date().getFullYear()}年`,
nameTextStyle :{
fontSize: 16
},
},
yAxis: {
name: '用户量',
nameTextStyle :{
fontSize: 20
},
axisLine:{
lineStyle:{
color:'#fff',
width:1
}
}
},
series: [
{
name: '高危',
type: 'bar',
color: '#CC0000',
barWidth: 15,
stack: 'one',
data: [5, 20, 36, 10, 10, 20,10,20,5,60,11,14]
},
{
name: '危险',
type: 'bar',
color: '#FF0000',
barWidth: 15,
stack: 'one',
data: [10, 10, 10, 10, 10, 10,10,20,5,10,11,12]
},
{
name: '低危',
type: 'bar',
color: '#CC6699',
barWidth: 15,
stack: 'one',
data: [10, 10, 10, 10, 10, 10,10,20,5,10,11,12]
},
{
name: '安全',
type: 'bar',
color: '#00CC33',
barWidth: 15,
stack: 'one',
data: [10, 10, 10, 10, 10, 10,10,20,5,10,11,12]
},
]
},

三、完成:

vue中封装echarts柱形图组件_数据