ECharts 图表
基于 ECharts 封装的 Vue3 图表组件,支持柱状图、折线图、饼图等常用图表类型。
🎯 在线演示:https://vue.youlai.tech/#/dashboard(控制台页面)
基本用法
vue
<template>
<ECharts :options="chartOptions" height="400px" />
</template>
<script setup lang="ts">
const chartOptions = ref({
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: [150, 230, 224, 218, 135, 147, 260],
type: 'line'
}
]
})
</script>柱状图
vue
<template>
<ECharts :options="barOptions" height="400px" />
</template>
<script setup lang="ts">
const barOptions = ref({
tooltip: {
trigger: 'axis'
},
xAxis: {
type: 'category',
data: ['一月', '二月', '三月', '四月', '五月', '六月']
},
yAxis: {
type: 'value'
},
series: [
{
name: '销售额',
type: 'bar',
data: [120, 200, 150, 80, 70, 110]
}
]
})
</script>饼图
vue
<template>
<ECharts :options="pieOptions" height="400px" />
</template>
<script setup lang="ts">
const pieOptions = ref({
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' },
{ value: 484, name: '联盟广告' },
{ value: 300, name: '视频广告' }
]
}
]
})
</script>折线图
vue
<template>
<ECharts :options="lineOptions" height="400px" />
</template>
<script setup lang="ts">
const lineOptions = ref({
tooltip: {
trigger: 'axis'
},
legend: {
data: ['访问量', '订单量']
},
xAxis: {
type: 'category',
data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
},
yAxis: {
type: 'value'
},
series: [
{
name: '访问量',
type: 'line',
data: [120, 132, 101, 134, 90, 230, 210]
},
{
name: '订单量',
type: 'line',
data: [220, 182, 191, 234, 290, 330, 310]
}
]
})
</script>Props
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
| options | ECharts 配置项 | EChartsCoreOption | - |
| width | 图表宽度 | string | '100%' |
| height | 图表高度 | string | '400px' |
功能特性
- ✅ 按需引入 - 只引入使用的图表类型,减小打包体积
- ✅ 响应式 - 自动监听容器尺寸变化,自动调整图表大小
- ✅ 配置响应 - 监听 options 变化,自动更新图表
- ✅ 自动销毁 - 组件卸载时自动销毁图表实例
内置图表类型
组件默认注册了以下图表类型:
- BarChart - 柱状图
- LineChart - 折线图
- PieChart - 饼图
扩展图表类型
如需使用其他图表类型(如雷达图、散点图等),需要在组件中注册:
typescript
// src/components/ECharts/index.vue
import { RadarChart, ScatterChart } from "echarts/charts";
echarts.use([
// ... 其他组件
RadarChart,
ScatterChart,
]);动态更新数据
vue
<template>
<ECharts :options="chartOptions" height="400px" />
<el-button @click="updateData">更新数据</el-button>
</template>
<script setup lang="ts">
const chartOptions = ref({
xAxis: {
type: 'category',
data: ['A', 'B', 'C', 'D', 'E']
},
yAxis: {
type: 'value'
},
series: [
{
type: 'bar',
data: [10, 20, 30, 40, 50]
}
]
})
function updateData() {
// 直接修改 options,图表会自动更新
chartOptions.value.series[0].data = [
Math.random() * 100,
Math.random() * 100,
Math.random() * 100,
Math.random() * 100,
Math.random() * 100
]
}
</script>仪表盘示例
项目的仪表盘页面 src/views/dashboard/index.vue 中有完整的图表使用示例。
