安装依赖 npm install echarts --save
<!-- 封装组件,创建一个容器,传入id确保每个图形的唯一性 -->
<template>
<div :ref="`echarts-bar${id}`" style="height:388px" />
</template>
// 导入echarts
import * as echarts from 'echarts';
export default {
/* 图形数据:
projectTotal 项目总数
actualArr 在建项目
contract 合同总金额
*/
props: {
id: String,
actualArr: {
type: Array,
default: () => [50, 22, 18, 33, 70, 40, 19, 33, 44, 25, 26, 20]
},
projectTotal: {
type: Array,
default: () => [70, 22, 55, 44, 75, 44, 25, 55, 61, 40, 40, 30]
},
contract: {
type: Array,
default: () => [333, 222, 350, 300, 366, 260, 240, 220, 100, 188, 100, 180]
},
},
data() {
myChart: null, // 用来存放图形实例
// x轴的类目名称列表 也可以传入对象单独设置类目的样式
xDataArr: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
}
mounted() {
// 页面加载初始化图形
this.myChart = echarts.init(this.$refs[`echarts-bar${this.id}`])
// 配置项
const options = {
tooltip: { // 鼠标悬浮提示图形信息
trigger: 'axis', // 触发类型, 通过坐标轴
axisPointer: { // 悬浮信息的配置
type: 'shadow' // 背景阴影类型
}
},
legend: { // 控制图形显隐的
icon: 'circle', // 可选的图标形状
// 与series的name属性值相对应 也可传入对象单独配置
data: ['在建项目', '合同总金额', '项目总数']
},
xAxis: { // x轴的配置
type: 'category',// 类目轴 非连续的数据, 常用于字符串 例如:"床" "前" "明" "月" "光"
data: this.xDataArr, // 类目列表
axisLabel: { // 坐标轴刻度标签的配置
color: '#333',
fontSize: 14
},
axisTick: {
show: false // 是否显示坐标轴刻度
},
},
yAxis: [ // y轴配置多个柱状图
{ // 左y轴配置
name: '(个)', // y轴的单位
type: 'value', // 数值轴
axisLine: { // y轴的侧边线
show: false
},
axisTick: { // y轴刻度线
show: false
},
splitLine: { // 网格线
lineStyle: {
type: 'dotted'
}
}
},
{ // 右y轴配置
name: '(万元)',
type: 'value', // 数值轴 常用于连贯的数据
axisLine: {
show: false
},
axisTick: {
show: false
},
splitLine: {
show: false
}
}
],
series: [
{
name: '项目总数', // 与lenged的值对应可以控制显隐
data: this.projectTotal, // 数据
type: 'bar', // 图形类型
barWidth: '8px', // 柱状图的宽度
itemStyle: { // 图形的配置
color: '#ff9502',
barBorderRadius: [180] // 柱状图的倒圆角
},
yAxisIndex: 0 // 与第一个y轴对应
},
{
name: '在建项目',
data: this.actualArr,
type: 'bar',
showBackground: false,
barWidth: '8px',
itemStyle: {
color: '#007AFF',
barBorderRadius: [180]
},
yAxisIndex: 0
},
{
name: '合同总金额',
data: this.contract,
type: 'line', // 折线图
symbolSize: 8, // 拐点符号的大小
symbol: 'circle', // 拐点符号的形状
itemStyle: {
color: 'rgb(255, 58, 48)', // 折线点的颜色
lineStyle: {
color: 'rgb(255, 58, 48)' // 折线的颜色
},
normal: {}, // 静态样式
emphasis: {} // // 鼠标移入后的样式
},
yAxisIndex: 1 // 对应y轴的第二个对象
}
]
}
// 给实例对象添加配置参数
this.myChart.setOption(options)
// 绑定监听事件
window.addEventListener('resize', this.resizeHandler)
},
beforeDestroy() { // 清理工作 避免内存泄漏
// 销毁监听事件
window.removeEventListener('resize', this.resizeHandler)
// 销毁 Echarts 实例
this.myChart.dispose()
},
methods: {
resizeHandler() { // 图形根据容器大小来进行缩放
this.myChart.resize()
}
}
}
效果图如下: