文章目录
前言
本次项目中负责了一个使用Echarts做的页面,涉及的图表类型有
柱状图(横竖两种)、折线图、气泡图、漏斗图、饼图
期间也遇到了不少问题,但是大部分的问题都是可以通过Echarts官方文档上找到解决办法的。下面记录一下问题及解决办法和Echarts的一些学习、码字心得。
一、常见问题记录
1.如何创建一个自适应的Echarts图表(动态给Echarts图表当前高度初始化+窗口缩放Echarts图表自适应)
讲道理这个问题一开始着实困扰我了大半天,因为页面需要自适应,根本不知道图表一开始具体的 Height 是多少。而且此次布局使用的是Flex布局,分左中右三块,每块上下各有一个图表,加一起是六个
。这里有两种解决思路,各有优缺点吧,这次用的第二个。
提供的思路并非最优解,只是在解决本次项目的过程中效果比较好,如果有什么更好的想法欢迎指出
动态高度初始化
思路一:通过css样式aspect-ratio(宽高比)解决
因为采用的是Flex布局
,而且是左中右三块,左右25%,中间50%,因此宽度是一定有的
此时,给图表的容器加上一个宽高比aspect-ratio,高度设置为100%
,图表在初始化的时候就能根据宽高比初始化出来。
优点:
- 操作简单,
css直接加
就ok - 对于
宽高比确定
的图表完美契合 - 图表
不会变形
缺点
- 分配的宽度过大的话会
影响整体布局
(超出盒子范围) 不适合
难以确定宽高比 或 图表不要求定型 的情况没办法使用
思路二:通过在父组件dom操作获取当前高度clientHeight(只读),作为参数调用子组件方法,在子组件获取到当前高度后初始化。
优点
布局不会乱
适合
难以确定宽高比 或 图表不要求定型 的情况
缺点
- 这样写的
高度是定死的
,除非再次传参初始化
,否则在不同大小的显示器上就只有刷新
后才能正常自适应
。
代码实现
父组件:关键代码
<Histogram ref="echarts1" />
// 有五个类似的组件
for (var i = 1; i <= 5; i++) {
this.$refs['echarts'+i].setHeight(document.getElementsByClassName('side-echarts-container')[0].clientHeight)
}
子组件:关键代码
<template>
<div>
<div id="hstogram" class="charts" :style="{'height':sideEchartsContainerHeight+'px','width':' 100%'}" />
</div>
</template>
<script>
import * as echarts from 'echarts'
import {
getBarGraphData } from '../../api/dataStatistics.js'
var option = {
// color: ['rgb(245,33,45)', 'rgb(255,229,143)', 'rgb(11,115,255)'],
color: [new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 1,
color: '#f00'
}, {
offset: 0,
color: '#f99'
}]),
new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 1,
color: 'rgb(249, 173, 21)'
}, {
offset: 0,
color: 'rgb(255,255,153)'
}]),
new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
offset: 1,
color: 'rgb(11,115,255)'
}, {
offset: 0,
color: 'rgba(0,255,255)'
}])
],
legend: {
textStyle: {
color: 'white'
},
top: 25
},
grid: {
show: true,
borderColor: 'rgba(255, 255, 255,0.5)'
},
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
}
},
xAxis: {
type: 'category',
axisLabel: {
interval: 0, // 显示全部x坐标
// rotate: 35,
color: 'rgba(255, 255, 255,1)'
},
nameTextStyle: {
align: 'center'
},
splitLine: {
show: true,
lineStyle: {
color: 'rgba(255, 255, 255,0.5)',
width: 1,
type: 'dashed'
}
}
},
yAxis: {
axisLabel: {
color: 'rgba(255, 255, 255,1)'
},
splitLine: {
lineStyle: {
color: 'rgba(255, 255, 255,0.5)',
width: 1,
type: 'dashed'
}
}
},
series: [
{
type: 'bar',
barWidth: 10,
itemStyle: {
//柱形图圆角,鼠标移上去效果,如果只是一个数字则说明四个参数全部设置为那么多
normal: {