vue实现饼图
使用 ECharts 实现 Vue 饼图
安装 ECharts 依赖
npm install echarts --save
在 Vue 组件中引入 ECharts
import * as echarts from 'echarts';
创建基础饼图组件
<template>
<div ref="chartDom" style="width: 600px; height: 400px;"></div>
</template>
<script>
export default {
mounted() {
this.initChart();
},
methods: {
initChart() {
const chart = echarts.init(this.$refs.chartDom);
const option = {
title: {
text: '示例饼图',
subtext: '数据展示',
left: 'center'
},
tooltip: {
trigger: 'item',
formatter: '{a} <br/>{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
data: ['直接访问', '邮件营销', '联盟广告', '视频广告', '搜索引擎']
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '50%',
data: [
{ value: 335, name: '直接访问' },
{ value: 310, name: '邮件营销' },
{ value: 234, name: '联盟广告' },
{ value: 135, name: '视频广告' },
{ value: 1548, name: '搜索引擎' }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
chart.setOption(option);
}
}
};
</script>
使用 Vue-ECharts 封装组件
安装 vue-echarts

npm install vue-echarts echarts --save
创建可复用的饼图组件
<template>
<v-chart :option="chartOption" autoresize />
</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: {
title: {
text: '自定义饼图',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left'
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#fff',
borderWidth: 2
},
label: {
show: false,
position: 'center'
},
emphasis: {
label: {
show: true,
fontSize: '18',
fontWeight: 'bold'
}
},
labelLine: {
show: false
},
data: [
{ value: 1048, name: '搜索引擎' },
{ value: 735, name: '直接访问' },
{ value: 580, name: '邮件营销' },
{ value: 484, name: '联盟广告' },
{ value: 300, name: '视频广告' }
]
}
]
}
};
}
};
</script>
<style scoped>
.v-chart {
height: 400px;
}
</style>
动态更新饼图数据
实现数据响应式更新

watch: {
chartData: {
handler(newVal) {
this.updateChart(newVal);
},
deep: true
}
},
methods: {
updateChart(data) {
this.chartOption.series[0].data = data;
this.$nextTick(() => {
if (this.chart) {
this.chart.setOption(this.chartOption);
}
});
}
}
饼图常见配置项
设置环形饼图
series: [{
type: 'pie',
radius: ['30%', '70%'],
...
}]
添加玫瑰图效果
series: [{
type: 'pie',
radius: [20, 120],
roseType: 'radius',
...
}]
设置多级饼图
series: [
{
type: 'pie',
radius: ['0%', '30%'],
...
},
{
type: 'pie',
radius: ['40%', '55%'],
...
}
]






