Vue3中如何将Highcharts饼图图例置于外部并显示百分比
Vue3 + Highcharts 饼图外部图例显示百分比解决方案
要实现饼图图例外置且显示百分比,可通过计算数据总和、转换数值格式来调整现有代码,具体修改如下:
1. 添加计算属性处理百分比
在script中新增computed属性,自动计算每个数据项的占比:
<script> export default { data() { return { isLoadingTypeOfId: false, options: { chart: { type: 'pie', spacingLeft: 0, height: 236, width: 240 }, credits: { enabled: false }, title: { text: '' }, legend: { enabled: false }, tooltip: { formatter() { return `${this.point.name}: ${Math.round(this.y)}` } }, plotOptions: { pie: { dataLabels: { enabled: false }, point: { events: { legendItemClick() { return false } } } } }, navigation: { buttonOptions: { enabled: false } }, series: [ { innerSize: '75%', data: [ { name: 'AA', y: 1, color: '#8DCEEB' }, { name: 'AA', y: 2, color: '#5A86EB' }, { name: 'AA', y: 3, color: '#9241F1' }, { name: 'AA', y: 4, color: '#515D6C' }, { name: 'AA', y: 5, color: '#FEC0CA' }, { name: 'AA', y: 6, color: '#F8B14D' } ], marker: { symbol: '\u25CF' } } ] } } }, computed: { pieLegendData() { const seriesData = this.options.series[0].data; // 计算数据总和,避免除以0异常 const total = seriesData.reduce((sum, item) => sum + item.y, 0); if (total === 0) { return seriesData.map(item => ({ ...item, percentage: 0 })); } // 转换为百分比并保留1位小数 return seriesData.map(item => ({ ...item, percentage: ((item.y / total) * 100).toFixed(1) })); } }, methods: { exportChart() { // 原导出逻辑保持不变 } } } </script>
2. 修改模板渲染逻辑
将模板中遍历的数据源替换为计算后的pieLegendData,并把原始数值替换为百分比:
<template> <el-card class="dvs-online-statistic"> <div class="dvs-online-statistic__chart-header"> <div class="dvs-online-statistic__chart-title">Type of ID</div> <div class="export-chart" @click="exportChart"> <i class="el-icon-upload2"></i> Export </div> </div> <div class="dvs-online-statistic__success-type" v-loading="isLoadingTypeOfId"> <highcharts :options="options" ref="chart"></highcharts> <div class="dvs-online-statistic__symbols"> <div class="dvs-online-statistic__series-value" v-for="item in pieLegendData" :key="item.name"> <div class="pie-point"> <span :style="{color: item.color}"> {{ options.series[0].marker.symbol }} </span> </div> <div> <div class="pie-legend-name"> {{ item.name }} </div> <div class="pie-legend-value"> {{ item.percentage }}% </div> </div> </div> </div> </div> </el-card> </template>
补充说明
- 若需调整小数位数,修改
toFixed(1)中的数字即可(例如toFixed(0)显示整数百分比) - 加入了总和为0的判断,避免出现NaN的异常情况
- 计算属性会随
options.series[0].data自动更新,适配异步加载数据的场景
内容的提问来源于stack exchange,提问作者Ilyas
相关产品推荐
相关产品推荐

