3、使用ECharts控件

发布时间 2023-12-07 18:45:06作者: zhaogaojian

这个示例使用了 ECharts 的饼图,并使用了 Vue.js 的生命周期钩子函数 mounted 来在组件挂载后初始化图表。在 data 中,chartData 存储了图表的数据,chartColors 存储了图表的颜色配置。在 methods 中,initECharts 方法用于初始化 ECharts 实例和配置项。

<template>
  <div>
    <!-- ECharts 图表容器 -->
    <div class="chart-container" ref="chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  data() {
    return {
      // 模拟的图表数据
      chartData: {
        xAxisData: ['A', 'B', 'C'],
        seriesData: [5, 3, 5],
      },
      // 图表颜色配置
      chartColors: ['#3398DB', '#FF6666', '#3CB371', '#FFD700', '#8B4513'],
    };
  },
  mounted() {
    // 使用固定数据配置 ECharts 实例
    this.initECharts();
  },
  methods: {
    initECharts() {
      const chartDom = this.$refs.chart;
      const myChart = echarts.init(chartDom);

      // ECharts 配置项
      const option = {
        title: {
          text: '示例数据',
          left: 'center',
          top: 20,
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        series: [{
          name: '示例数据',
          type: 'pie',
          radius: '55%',
          center: ['50%', '50%'],
          data: this.chartData.xAxisData.map((name, index) => ({
            name,
            value: this.chartData.seriesData[index],
            itemStyle: {
              color: this.chartColors[index % this.chartColors.length],
            },
          })),
          label: {
            show: true,
            formatter: '{b} : {c} ({d}%)',
          },
        }],
      };

      // 使用配置项设置图表
      myChart.setOption(option);
    },
  },
};
</script>

<style scoped>
.chart-container {
  height: 300px;
  /* 设置图表容器的高度 */
}
</style>