1.安装:npm install echarts --save(我的版本是4.9.0,这里展示的是折线图)
![](https://img.haomeiwen.com/i20720482/a8dc57c2dcf65a20.png)
2.引入使用
// 全部引入
// import echarts from 'echarts';
// 按需引入
// 1.引入基本模板
const echarts = require('echarts/lib/echarts');
// 2.引入折线图
require('echarts/lib/chart/line');
// 3.引入提示框,标题组件,工具栏,内置型数据区域缩放组件,连续型视觉映射等组件
require('echarts/lib/component/tooltip');
require('echarts/lib/component/title');
require('echarts/lib/component/toolbox');
require('echarts/lib/component/dataZoom');
require('echarts/lib/component/visualMap');
require('echarts/lib/component/markLine');
3.为echarts准备一个dom容器,定好宽高
<div ref="myChart" class="charts"></div>
4.使用
private myChart: any;
// 初始化折线图
private initEcharts() {
const list = [{time:1,count:1}];//自己的数据,我以time作为横坐标,count作为纵坐标
const options: any = {
type: 'category',
title: {
text: '实时统计'
},
tooltip: {
trigger: 'axis'
},
xAxis: {
data: list.map(item => `${this.search.dateline} ${item.time}`)
},
yAxis: {
splitLine: {
show: false
}
},
toolbox: {
left: 'center',
feature: {
restore: {},
saveAsImage: {}
}
},
dataZoom: [
{
startValue: '2020-01-01 00:00'
},
{
type: 'inside'
}
],
visualMap: {
top: 10,
right: 10,
pieces: [
{
gt: 0,
lte: 50,
color: '#096'
},
{
gt: 50,
lte: 100,
color: '#ffde33'
}
],
outOfRange: {
color: '#999'
}
},
series: {
name: '用户数',
type: 'line',
data: list.map(item => item.count),
markLine: {
silent: true,
data: [
{
yAxis: 50
},
{
yAxis: 100
}
]
}
}
};
this.myChart = echarts.init(this.$refs.myChart as HTMLCanvasElement);
this.myChart.setOption(options);
//在初始化图表之后,重新加载(我这里是为了自适应宽度)
setTimeout(() => {
this.myChart.resize();
}, 500);
}
option可以随意根据自己需求改变,这里是实例地址:https://echarts.apache.org/examples/zh/index.html
想要那种可以直接复制
5.如果想要跟随浏览器窗口的变化,自适应,需要加一个监听
window.addEventListener('resize', () => {
this.myChart.resize();
});
6.在过程中遇到的问题
-1.如果你用了eslint检测,禁止使用require语句
Require statement not part of import statement.(@typescript-eslint/no-var-requires)
![](https://img.haomeiwen.com/i20720482/b90b4d1714f5507e.png)
那么只好改一下了
.eslintrc.js中的 rules:
rules: {
'@typescript-eslint/no-var-requires': 0
}
-2.按照文档上写的用import引入,就报了这个错
![](https://img.haomeiwen.com/i20720482/7ae808407a660e5e.png)
exportant 'default' (imported as 'Echarts') was not found in 'echarts
最后的写法是换成了require
const echarts = require('echarts/lib/echarts');
-3.在Chrome浏览器,鼠标滚动,就会出现这个error
![](https://img.haomeiwen.com/i20720482/a4ede348dc048100.png)
Unable to preventDefault inside passive event listener invocation
调用 preventDefault 函数来阻止事件的默认行为,但Chrome浏览器为了使页面浏览更顺畅,默认忽略,需要主动告诉浏览器我不调用 preventDefault 函数来阻止事件事件行为,这样就不报错了
详细可参考:https://www.freesion.com/article/59134650/
我这里研究了一个解决办法,就是下载echarts.min.js,放进项目里面,在import进来
然后改一下echarts.min.js这个文件
![](https://img.haomeiwen.com/i20720482/cb7e6f53ef3c6ed3.png)
但是我最终还是决定不使用这个方法,因为这个文件实在是有点大,如果按需生成文件,那么下次在想使用其他功能,还得重新下载,对版本控制也不友好,反正不影响使用,直接忽略那个报错
网友评论