vue实现复杂饼图
使用 ECharts 实现复杂饼图
ECharts 是一个功能强大的数据可视化库,支持复杂的饼图配置,包括嵌套饼图、环形图、自定义标签等。
安装 ECharts:
npm install echarts --save
基础饼图实现:
<template>
<div ref="chart" style="width: 600px; height: 400px;"></div>
</template>
<script>
import * as echarts from 'echarts';
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chartDom = this.$refs.chart;
const myChart = echarts.init(chartDom);
const option = {
title: {
text: '基础饼图示例',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
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: '视频广告' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
myChart.setOption(option);
}
}
};
</script>
实现环形饼图
修改 radius 属性即可创建环形图:

series: [
{
name: '访问来源',
type: 'pie',
radius: ['40%', '70%'], // 内半径40%,外半径70%
data: [
// 数据同上
]
}
]
实现嵌套饼图(多层饼图)
通过多个 series 叠加实现:
series: [
{
name: '外层',
type: 'pie',
radius: ['50%', '70%'],
label: {
show: false
},
data: [
{ value: 335, name: 'A' },
{ value: 310, name: 'B' },
{ value: 234, name: 'C' }
]
},
{
name: '内层',
type: 'pie',
radius: ['0', '30%'],
label: {
position: 'inner'
},
data: [
{ value: 100, name: 'A1' },
{ value: 90, name: 'A2' },
{ value: 145, name: 'A3' }
]
}
]
自定义饼图样式
可以自定义每个扇区的样式:
data: [
{
value: 1048,
name: '搜索引擎',
itemStyle: {
color: '#c23531',
borderWidth: 2,
borderColor: '#fff'
}
},
// 其他数据项...
]
添加交互效果
配置 tooltip 和 emphasis 增强交互:

tooltip: {
trigger: 'item',
formatter: function(params) {
return `${params.seriesName}<br/>
${params.marker} ${params.name}<br/>
数值: ${params.value}<br/>
占比: ${params.percent}%`;
}
},
emphasis: {
scale: true,
scaleSize: 5,
label: {
show: true,
fontSize: '20',
fontWeight: 'bold'
}
}
响应式处理
添加窗口大小变化监听:
mounted() {
this.initChart();
window.addEventListener('resize', this.handleResize);
},
methods: {
handleResize() {
this.myChart && this.myChart.resize();
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
}
使用 Vue-ECharts 组件
对于更简单的集成,可以使用 vue-echarts 封装组件:
npm install vue-echarts echarts --save
使用示例:
<template>
<v-chart :option="chartOption" style="height: 400px" />
</template>
<script>
import { use } from 'echarts/core';
import { PieChart } from 'echarts/charts';
import {
TitleComponent,
TooltipComponent,
LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import VChart from 'vue-echarts';
use([
TitleComponent,
TooltipComponent,
LegendComponent,
PieChart,
CanvasRenderer
]);
export default {
components: {
VChart
},
data() {
return {
chartOption: {
// 同上配置
}
};
}
};
</script>
以上方法提供了从基础到高级的 Vue 中实现复杂饼图的完整方案,可根据实际需求选择合适的实现方式。






