Table of contents
echarts official website
Introduce echarts into the project
[1] download
npm install echarts
[2-1] Full import
import * as echarts from 'echarts';
Full import refers to the introduction of the core module of echarts, all charts and components that can be used in charts.
If your project only uses one or a few charts, it is recommended to use on-demand import. . .
[2-2] Import on demand
- Introduce echarts core module
import * as echarts from "echarts/lib/echarts";
- Import the required charts and components as needed, as follows (bar chart and funnel chart are required)
// 引入柱状图以及漏斗图 import { FunnelChart, BarChart } from 'echarts/charts'; // 引入组件 import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'; // 注册 echarts.use([FunnelChart, BarChart, GridComponent, TitleComponent, TooltipComponent, LegendComponent]);
- Configuration item rendering dom
- [1] in react
const chartDom = useRef() const option = { ...} const myChart = echarts.init(chartDom.current) myChart.setOption(option)
- [2] in vue
The two are only different in the way of obtaining domconst dom = document.querySelector('.chartDom') const option = { ...} const myChart = echarts.init(dom) myChart.setOption(option)
- [1] in react
Problem - importing only core modules
Take the quick start case of echarts official website as an example to explain some problems that will occur if only the core module is introduced and the option configuration is performed~
- [1] Introduce echarts core module
import * as echarts from "echarts/lib/echarts";
- [2] Configure option and render dom
At this time, the following error will be reported as followsuseEffect(async () => { const option = { title: { text: 'ECharts 入门示例' }, tooltip: { }, legend: { data: ['销量'] }, xAxis: { data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] }, yAxis: { }, series: [ { name: '销量', type: 'bar', data: [5, 20, 36, 10, 10, 20] } ] } const myFunnelChart = echarts.init(funnelchartDom.current) myFunnelChart.setOption(option) },[]);
to import the required components according to the above error report
No error is reported at this time, but the displayed chart is as follows (the desired effect is not achieved),import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'; echarts.use([ GridComponent, TitleComponent, TooltipComponent, LegendComponent]);
but no error is reported at this time, and it becomes difficult to find errors at this time. In fact, the chart is not imported as needed. After introducing the required chart It can be displayed normally~import { BarChart } from 'echarts/charts'; import { GridComponent, TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components'; echarts.use([ BarChart, GridComponent, TitleComponent, TooltipComponent, LegendComponent]);
Of course, few people will make this mistake in this problem. It is only possible to introduce unfamiliar processes for the first time~