PieChart.vue 2.87 KB
<template>
  <div>
    <p class="line-color-title">{{title}}</p>
    <div v-if="data" ref="pieChart" style="margin-top:10px;width: 100%; height:24.5vh;"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import resize from './../mixin/resize'
export default {
  name: 'PieChart',
  mixins:[resize],
  props: {
    title:{
      type: String,
      default: '',
    },
    data: {
      type: Array,
      default: () => [],
    },
    colors: {
      type: Array,
      default: () => ['#50CEFB', '#5850FF','#FBBE50','#90D55C','#FDDB93','#A1EDFF','#6EA3FF','#FF5A92','#BCCAFF','#9F6EFF'],
    },
  },
  data() {
    return {
      dynamicRichStyles: {},
    };
  },

  mounted() {
    this.initChart(this.$refs.pieChart);
    this.drawChart();
    this.dynamicResizeChart();
  },
  methods: {
    generateRichStyles() {
      this.colors.forEach((color, index) => {
        this.dynamicRichStyles['style' + index] = {
          color: color,
          fontWeight: 'bold',
          fontSize: '17px'
        };
      });
    },
    createFormatter(params) {
      const dataIndex = params.dataIndex;
      const dataItem = this.data[dataIndex]; // 获取当前索引下的数据项
      const styleKey = 'style' + (dataIndex % this.colors.length);

      // 确保dataItem存在,并且displayQuantity已定义
      const displayQuantityText = dataItem && dataItem.displayQuantity !== undefined && dataItem.displayQuantity !== null
          ? '('+dataItem.displayQuantity + '人' + ')'
          : '';

      return `{${styleKey}|${params.value}%}\n\n{b|${params.name}${displayQuantityText}}`;
    },


    drawChart() {
      this.generateRichStyles(); // 生成动态样式
      const chart = echarts.init(this.$refs.pieChart);

      const option = {
        // tooltip: {
        //   trigger: 'item',
        // },
        legend: {
          show: false,
        },
        series: [
          {
            type: 'pie',
            radius: ['40%', '60%'],
            avoidLabelOverlap: false,
            minAngle: 50, // 设置最小角度为50度,针对传入的数据为0
            label: {
              show: true,
              position: 'outside',
              formatter: this.createFormatter, // 引用 formatter 函数
              rich: this.dynamicRichStyles, // 使用动态生成的样式
            },
            labelLine: {
              show: true
            },
            data: this.data,
            itemStyle: {
              color: (params) => {
                return this.colors[params.dataIndex];
              },
            },
          },
        ],
      };

      chart.setOption(option);
    },
  },
};
</script>

<style lang="scss" scoped>
/* 您可以根据需要添加自定义样式 */
@media screen and (min-resolution: 2dppx) {
  /* 针对高分辨率显示屏的样式调整 */
  .pieChart {
    height: 28vh; /* 可能需要更大的高度 */
  }
}
</style>