<template>
  <!-- 为 ECharts 准备一个定义了宽高的 DOM -->
  <div :id="uuid" :style="style"></div>
</template>
<script>
import * as echarts from "echarts";

const genID = () => new Date().getTime();
export default {
  props: {
    height: {
      type: String,
      default: "400px",
    },
    width: {
      type: String,
      default: "600px",
    },
    options: {
      type: Object,
      default: null,
    },
  },
  computed: {
    style() {
      return {
        height: this.height,
        width: this.width,
      };
    },
  },
  data() {
    return {
      uuid: null,
      myChart: null,
    };
  },
  watch: {
    width() {
      // 响应式改图表的宽度
      if (this.myChart) {
        this.myChart.resize({
          animation: {
            duration: 300, // 300ms 内完成尺寸变化
          },
        });
      }
    },
    options() {
      if (this.myChart) {
        this.myChart.setOption(this.options, {
          notMerge: true,
        });
      }
    },
  },
  created() {
    this.uuid = genID();
  },
  mounted() {
    // 基于准备好的dom,初始化echarts实例
    this.myChart = echarts.init(document.getElementById(this.uuid));

    // 使用刚指定的配置项和数据显示图表。
    this.myChart.setOption(this.options);
  },
};
</script>
// 使用
const options = {
  title: {
    text: "ECharts 入门示例",
  },
  tooltip: {},
  xAxis: {
    data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
  },
  yAxis: {},
  series: [
    {
      name: "销量",
      type: "bar",
      data: [5, 20, 36, 10, 10, 20],
    },
  ],
};
<MyEcharts :options="options" :width="width" />
Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐