可以尝试以下代码:

import { defineComponent, onMounted, PropType } from 'vue';
import * as echarts from 'echarts';

export default defineComponent({
  name: 'EchartsChart',
  props: {
    width: {
      type: String,
      required: true,
    },
    height: {
      type: String,
      required: true,
    },
    option: {
      type: Object as PropType<echarts.EChartsOption>,
      required: true,
    },
    id: {
      type: String,
      required: true,
    },
  },
  setup(props) {
    let chart: echarts.ECharts;

    onMounted(() => {
      chart = echarts.init(document.getElementById(props.id)!);
      chart.setOption(props.option);

      window.addEventListener('resize', () => {
        chart.resize();
      });
    });

    return {
      chart,
    };
  },
  render() {
    return <div id={this.id} style={{ width: this.width, height: this.height }}></div>;
  },
});

该组件将会使用echarts库来生成图表,并且会自动适应窗口大小。在setup函数中,我们使用onMounted钩子函数来初始化chart变量,并在窗口大小改变时调用resize方法。使用render函数来渲染图表的容器。

使用方式如下:

<template>
  <EchartsChart width='100%' height='300px' :option='option' id='myChart' />
</template>

<script lang='ts'>
import { defineComponent } from 'vue';
import EchartsChart from './EchartsChart.vue';

export default defineComponent({
  name: 'App',
  components: {
    EchartsChart,
  },
  data() {
    return {
      option: {
        // ...
      },
    };
  },
});
</script>

注意,option属性的类型需要是echarts.EChartsOption,这是echarts库中定义的类型。


原文地址: https://www.cveoy.top/t/topic/mK93 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录