Vue集成echarts十问

一、如何安装和引入

安装

1
npm install echarts --save

其他安装方式:官网参考

全局引入

1
2
// 全局引入
import echarts from 'echarts';

按需引入

1
2
3
4
5
6
7
8
9
10
11
12
// 引入echarts主程序
import echarts from 'echarts/lib/echarts'
// 引入条形图
import 'echarts/lib/chart/bar'
// 引入grid组件
import 'echarts/lib/component/grid'
// 引入title组件
import 'echarts/lib/component/title'
// 引入tooltip组件
import 'echarts/lib/component/tooltip'
// 引入legend组件
import 'echarts/lib/component/legend'

推荐使用按需引入,以减少包体积大小

二、如何初始化

在template中添加一个div标签,并设置其宽高,作为echarts初始化的DOM容器

1
2
3
<template>
<div ref="chart" style="width: 500px; height: 500px;"></div>
</template>

注意:未设置DOM容器宽高时,echarts将不会渲染

在mounted钩子中初始化echarts实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
export default {
data() {
return {
// 维护图表实例,在后面重绘时使用
chartInstance: ''
}
},
mounted () {
// 图表选项
const options = {};
// 初始化图表实例
this.chartInstance = echarts.init(this.$refs.chart);
// 设置图表选项
this.chartInstance.setOptions(options);
}
}

三、如何响应数据变化进行重绘

将options作为计算属性,根据传入的props进行计算,当依赖的props变化时,options同时进行变化,然后监听options变化进行重绘。一个简单的条形图示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
export default {
props: {
// 数据示例:[{cateogry: 'Mon', value: 100}, {category: 'Tue', value: 200}]
list: {
type: Array,
default: () => []
}
},
data() {
return {
// 维护echarts实例,初始化时设置,重绘时使用
chartInstance: ''
}
},
computed: {
// options作为计算属性,依赖list属性计算所得
options() {
const xAxisData = this.list.map(item => item.category);
const barData = this.list.map(item => item.value);
return {
xAxis: {
type: 'category',
data: xAxisData
},
yAxis: {
type: 'value'
},
series: [{
data: barData,
type: 'bar'
}]
};
}
},
watch: {
// 监听options,发生变化时,使用新值进行图表重绘
options(newValue) {
this.chartInstance && this.chartInstance.setOption(newValue);
}
},
mounted() {
// 当dom挂载之后进行echarts初始化
this.chartInstance = echarts.init(this.$refs.chart);
this.chartInstance.setOption(this.options);
}
}

四、如何自适应容器大小

1、获取外部容器(组件父元素)的大小

2、设置图表的容器的大小为获取的组件父元素大小

修改mounted钩子中echarts初始化代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
export default {
mounted() {
// 获取组件父元素及其计算样式
const parentNode = this.$el.parentNode;
const parentNodeStyle = window.getComputedStyle(parentNode);
// 设置图表的容器大小为组件父元素大小
this.$refs.chart.style.width = parentNodeStyle.width;
this.$refs.chart.style.height = parentNodeStyle.height;
// 初始化图表
this.chartInstance = echarts.init(this.$refs.chart);
this.chartInstance.setOption(this.options);
}
}

五、如何方便地实现复杂的自定义tooltip

echarts通过tooltip的formatter属性,支持用户对tooltip进行自定义,formatter属性有两个类型,一个是字符串模板,