1. 安装与引入
在 Vue3 项目中使用 ECharts,推荐通过 npm 安装,并结合按需引入减小打包体积。
npminstallecharts按需引入(推荐):在项目中新建src/utils/echarts.js统一管理引入:
// src/utils/echarts.jsimport*asechartsfrom'echarts/core';import{BarChart,LineChart,PieChart,ScatterChart,GaugeChart}from'echarts/charts';import{GridComponent,TooltipComponent,LegendComponent,TitleComponent}from'echarts/components';import{CanvasRenderer}from'echarts/renderers';echarts.use([BarChart,LineChart,PieChart,ScatterChart,GaugeChart,GridComponent,TooltipComponent,LegendComponent,TitleComponent,CanvasRenderer]);exportdefaultecharts;2. 在 Vue3 组件中使用
2.1 基础封装
创建一个可复用的图表组件src/components/BaseChart.vue:
<template> <div ref="chartRef" class="chart-container"></div> </template> <script setup> import { ref, onMounted, onBeforeUnmount, watch } from 'vue'; import echarts from '@/utils/echarts'; const props = defineProps({ option: { type: Object, required: true } }); const chartRef = ref(null); let chart = null; onMounted(() => { chart = echarts.init(chartRef.value); chart.setOption(props.option); }); // 监听 option 变化并更新图表 watch( () => props.option, (newOption) => { chart?.setOption(newOption); }, { deep: true } ); // 组件卸载时销毁实例,释放内存 onBeforeUnmount(() => { chart?.dispose(); }); </script> <style scoped> .chart-container { width: 100%; height: 400px; } </style>2.2 在页面中使用
<template> <div class="dashboard"> <BaseChart :option="barOption" /> </div> </template> <script setup> import { reactive } from 'vue'; import BaseChart from '@/components/BaseChart.vue'; // 使用 reactive 定义响应式配置 const barOption = reactive({ title: { text: '月度销售额' }, tooltip: {}, xAxis: { data: ['一月', '二月', '三月', '四月', '五月', '六月'] }, yAxis: {}, series: [ { name: '销售额', type: 'bar', data: [120, 200, 150, 80, 170, 210] } ] }); </script>2.3 响应式处理
当浏览器窗口大小变化时,需要手动触发图表重绘:
<script setup> import { onMounted, onBeforeUnmount } from 'vue'; let chart = null; const handleResize = () => { chart?.resize(); }; onMounted(() => { window.addEventListener('resize', handleResize); }); onBeforeUnmount(() => { window.removeEventListener('resize', handleResize); chart?.dispose(); }); </script>3. 常用图表类型
ECharts 内置了 20 多种图表类型,这里介绍最常用的几种。
3.1 折线图
折线图适合展示数据随时间变化的趋势:
constoption={xAxis:{type:'category',data:['周一','周二','周三','周四','周五']},yAxis:{type:'value'},series:[{name:'访问量',type:'line',data:[820,932,901,934,1290],smooth:true// 平滑曲线}]};3.2 饼图
饼图用于展示数据的占比分布:
constoption={series:[{type:'pie',data:[{value:1048,name:'搜索引擎'},{value:735,name:'直接访问'},{value:580,name:'邮件营销'}]}]};3.3 散点图
散点图适合展示两个变量之间的关系:
constoption={xAxis:{type:'value'},yAxis:{type:'value'},series:[{type:'scatter',data:[[10,20],[15,35],[20,30],[25,50]]}]};4. 自定义样式核心技巧
ECharts 的强大之处在于其高度可定制的样式体系。下面从几个维度展开讲解。
4.1 主题定制
ECharts 支持注册自定义主题,实现全局样式统一:
// 注册主题echarts.registerTheme('myTheme',{color:['#5470c6','#91cc75','#fac858','#ee6666'],backgroundColor:'#f8f9fa',textStyle:{fontFamily:'Microsoft YaHei',fontSize:14}});// 使用主题初始化constchart=echarts.init(chartRef.value,'myTheme');4.2 颜色与渐变
ECharts 支持线性渐变、径向渐变和纹理填充:
series:[{type:'bar',data:[120,200,150,80,170,210],itemStyle:{// 线性渐变color:{type:'linear',x:0,y:0,x2:0,y2:1,colorStops:[{offset:0,color:'#83bff6'},{offset:1,color:'#2f89fc'}]},borderRadius:[8,8,0,0]// 圆角}}]4.3 图例与提示框样式
constoption={legend:{top:'5%',textStyle:{color:'#666',fontSize:13},itemWidth:18,itemHeight:12},tooltip:{trigger:'axis',backgroundColor:'rgba(255,255,255,0.95)',borderColor:'#ddd',textStyle:{color:'#333'},axisPointer:{type:'shadow',shadowStyle:{color:'rgba(150,150,150,0.1)'}}}};4.4 坐标轴美化
4.5 按 data 参数类型设置不同样式
实际项目中,series.data的数据结构并不总是单一的数值数组,可能是对象数组、二维数组等。ECharts 允许在data中为每个数据项单独配置itemStyle,从而根据数据类型的不同设置差异化样式:
constoption={tooltip:{trigger:'axis'},legend:{top:'5%'},series:[{name:'销售额',type:'bar',// 数值数组:统一使用默认样式data:[120,200,150,80,170,210]},{name:'利润',type:'bar',// 对象数组:为每个数据项单独设置样式data:[{value:45,itemStyle:{color:'#91cc75'}},{value:88,itemStyle:{color:'#fac858'}},{value:66,itemStyle:{color:'#ee6666'}},{value:30,itemStyle:{color:'#73c0de'}},{value:92,itemStyle:{color:'#3ba272'}},{value:58,itemStyle:{color:'#fc8452'}}]},{name:'散点分布',type:'scatter',// 二维数组:按数值区间动态取色data:[[10,20],[15,35],[20,30],[25,50]],itemStyle:{color:(params)=>{// 根据 y 值大小返回不同颜色returnparams.value[1]>40?'#ee6666':'#5470c6';}}}]};要点说明:
- 数值数组:
data: [120, 200, 150]是最简单的形式,所有数据项共用series.itemStyle中配置的统一样式。 - 对象数组:
data: [{ value: 45, itemStyle: {...} }]可在每个数据项内部单独覆盖itemStyle,实现「逐项差异化」配色,常用于柱状图、饼图。 - 二维数组:
data: [[10, 20], [15, 35]]常用于散点图,此时itemStyle.color可写成回调函数,根据params.value的数值动态返回颜色。 - 回调函数取色:
color: (params) => {...}是「按数据值设置样式」的核心手段,可基于数值大小、区间、名称等条件返回任意颜色或渐变对象。 - 在 Vue3 中动态切换:只需修改
reactive中的option,BaseChart组件通过watch自动调用setOption完成样式更新。
5. 进阶自定义实战
5.1 动态数据更新
实际业务中,图表数据往往需要实时刷新,在 Vue3 中结合setInterval实现:
// 模拟定时更新数据consttimer=setInterval(()=>{constnewData=[Math.random()*300,Math.random()*300,Math.random()*300];chart.setOption({series:[{data:newData}]});},2000);// 组件卸载时清除定时器onBeforeUnmount(()=>{clearInterval(timer);});5.2 事件交互
ECharts 提供了丰富的事件监听能力:
// 点击事件chart.on('click',(params)=>{console.log('点击了',params.name,'数值为',params.value);});// 图例切换事件chart.on('legendselectchanged',(params)=>{console.log('图例状态变化',params.selected);});5.3 自定义系列(以仪表盘为例)
constoption={series:[{type:'gauge',min:0,max:100,progress:{show:true,width:18,itemStyle:{color:{type:'linear',x:0,y:0,x2:1,y2:0,colorStops:[{offset:0,color:'#00c6ff'},{offset:1,color:'#0072ff'}]}}},axisLine:{lineStyle:{width:18}},data:[{value:72,name:'完成率'}]}]};6. 性能优化建议
- 按需引入:使用
echarts/core按需加载图表和组件,避免全量引入导致包体积过大。 - 合理使用
notMerge:当数据完全变化时,setOption(option, true)可避免不必要的合并计算。 - 及时销毁实例:在组件卸载时调用
chart.dispose()释放内存。 - 大数据量优化:开启
sampling: 'lttb'对折线图数据进行降采样。
7. 总结
本文从 Vue3 项目的角度出发,介绍了 ECharts 的安装引入、组件封装、常用图表类型,并重点讲解了主题定制、渐变配色、坐标轴美化等自定义样式技巧,最后补充了动态更新、事件交互和性能优化等进阶内容。
掌握这些核心能力后,你就能在 Vue3 项目中根据业务需求打造出既美观又实用的数据可视化作品。建议在实际项目中多尝试不同的配置组合,逐步形成自己的样式规范。