vue3.2实现echart图表绘制
时间: 2025-07-04 18:20:40 浏览: 6
### 集成ECharts至Vue 3.2
对于Vue 3.2版本而言,集成ECharts的过程涉及安装依赖、全局注册或者局部组件化使用以及编写具体的图表逻辑。
#### 安装ECharts包
为了在项目中利用ECharts的功能,需先通过npm安装对应的库:
```bash
npm install echarts --save
```
此命令会将`echarts`作为项目的依赖项加入到`package.json`文件之中[^1]。
#### 全局引入或按需加载
一种方法是在应用入口处(`main.js`)进行全局引入,以便在整个应用程序范围内访问ECharts:
```javascript
import * as echarts from 'echarts';
app.config.globalProperties.$echarts = echarts;
```
另一种更推荐的方式是采用按需加载,在具体使用的组件内部导入所需的模块,减少打包体积。这种方式特别适合大型项目中的性能优化[^2]。
#### 创建带有ECharts的Vue组件
下面给出一个简单的例子来说明如何在一个Vue组件里创建柱状图:
```html
<template>
<div ref="chartRef" style="width: 600px;height:400px;"></div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
const chartRef = ref(null)
onMounted(() => {
const myChart = echarts.init(chartRef.value);
let option = {
title : {
text: '某地区蒸发量和降水量',
subtext: '纯属虚构'
},
tooltip : {
trigger: 'axis'
},
legend: {
data:['蒸发量','降水量']
},
toolbox: {
show : true,
feature : {
mark : {show: true},
dataView : {show: true, readOnly: false},
magicType : {show: true, type: ['line', 'bar']},
restore : {show: true},
saveAsImage : {show: true}
}
},
calculable : true,
xAxis : [
{
type : 'category',
data : ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'蒸发量',
type:'bar',
data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
markPoint : {
data : [
{type : 'max', name: '最大值'},
{type : 'min', name: '最小值'}
]
},
markLine : {
data : [
{type : 'average', name: '平均值'}
]
}
},
{
name:'降水量',
type:'bar',
data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3],
markPoint : {
data : [
{name : '年最高', value : 182.2, xAxis: 7, yAxis: 183},
{name : '年最低', value : 2.3, xAxis: 11, yAxis: 3}
]
},
markLine : {
data : [
{type : 'average', name : '平均值'}
]
}
}
]
};
myChart.setOption(option);
})
</script>
```
上述代码展示了如何定义一个包含两个系列(蒸发量与降水量)的双轴柱状图,并设置了相应的样式选项[^3]。
阅读全文
相关推荐

















