vue实现关联饼图
Vue 实现关联饼图
关联饼图通常指多个饼图之间通过交互或数据联动展示关联关系。以下是基于 Vue 和 ECharts 的实现方法:
安装依赖
确保项目中已安装 ECharts 和 Vue-ECharts:

npm install echarts vue-echarts
基础组件封装
创建一个可复用的饼图组件(PieChart.vue):
<template>
<v-chart class="chart" :option="option" :autoresize="true" />
</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([
PieChart,
TitleComponent,
TooltipComponent,
LegendComponent,
CanvasRenderer
]);
export default {
components: { VChart },
props: {
chartData: {
type: Array,
required: true
},
title: {
type: String,
default: ""
}
},
computed: {
option() {
return {
title: { text: this.title, left: "center" },
tooltip: { trigger: "item" },
legend: { orient: "vertical", right: 10, top: "center" },
series: [{
name: this.title,
type: "pie",
radius: ["40%", "70%"],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 10 },
label: { show: false },
emphasis: { label: { show: true } },
data: this.chartData
}]
};
}
}
};
</script>
<style scoped>
.chart {
height: 400px;
}
</style>
实现关联交互
在父组件中实现数据联动(示例为两个关联饼图):

<template>
<div class="container">
<pie-chart
ref="chart1"
:chart-data="data1"
title="主分类"
@chart-click="handleChartClick"
/>
<pie-chart
ref="chart2"
:chart-data="data2"
title="子分类"
/>
</div>
</template>
<script>
import PieChart from "./PieChart.vue";
export default {
components: { PieChart },
data() {
return {
rawData: {
"电子产品": [
{ value: 35, name: "手机" },
{ value: 25, name: "笔记本" }
],
"服装": [
{ value: 30, name: "男装" },
{ value: 10, name: "女装" }
]
},
data1: [],
data2: []
};
},
mounted() {
this.initData();
},
methods: {
initData() {
this.data1 = Object.keys(this.rawData).map(name => ({
name,
value: this.rawData[name].reduce((sum, item) => sum + item.value, 0)
}));
},
handleChartClick(params) {
if (params.data) {
this.data2 = this.rawData[params.data.name];
}
}
}
};
</script>
<style>
.container {
display: flex;
gap: 20px;
}
</style>
高级联动功能
通过 ECharts 的 connect 实现视图级联动:
// 在父组件 mounted 中添加
import { connect } from "echarts";
mounted() {
this.$nextTick(() => {
const chart1 = this.$refs.chart1.$refs.chart;
const chart2 = this.$refs.chart2.$refs.chart;
connect([chart1, chart2]);
});
}
动态数据更新
使用 watch 实现响应式数据更新:
watch: {
data2(newVal) {
this.$refs.chart2.option.series[0].data = newVal;
this.$refs.chart2.chart.setOption(this.$refs.chart2.option);
}
}
注意事项
- 确保为每个数据项设置唯一的
name属性以便正确联动 - 复杂场景可使用 Vuex 或 Pinia 管理共享状态
- 大数据量时建议启用 ECharts 的数据裁剪功能:
series: [{ // ... large: true, largeThreshold: 500 }]






