3、使用ECharts控件

這個示例使用了 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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章