Vue+ts项目中封装echarts组件
    		       		warning:
    		            这篇文章距离上次修改已过450天,其中的内容可能已经有所变动。
    		        
        		                
                在Vue+ts项目中封装ECharts组件,你可以创建一个Vue组件,并使用ECharts库来创建图表。以下是一个简单的示例:
- 安装ECharts依赖:
 
npm install echarts --save- 创建ECharts组件:
 
<template>
  <div :id="id" :style="{ width: width, height: height }"></div>
</template>
 
<script lang="ts">
import { defineComponent, onMounted, onUnmounted, ref, watch } from 'vue';
import * as echarts from 'echarts';
 
export default defineComponent({
  name: 'EChartsComponent',
  props: {
    option: {
      type: Object,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    width: {
      type: String,
      default: '600px'
    },
    height: {
      type: String,
      default: '400px'
    }
  },
  setup(props) {
    let chartInstance = ref<echarts.ECharts | null>(null);
 
    onMounted(() => {
      chartInstance.value = echarts.init(document.getElementById(props.id) as HTMLDivElement);
      chartInstance.value?.setOption(props.option);
    });
 
    onUnmounted(() => {
      chartInstance.value?.dispose();
    });
 
    watch(() => props.option, (newOption) => {
      chartInstance.value?.setOption(newOption);
    });
 
    return {
      chartInstance,
      ...props
    };
  }
});
</script>- 使用ECharts组件:
 
<template>
  <EChartsComponent :option="chartOption" id="myChart" />
</template>
 
<script lang="ts">
import { defineComponent, reactive } from 'vue';
import EChartsComponent from './EChartsComponent.vue';
 
export default defineComponent({
  components: {
    EChartsComponent
  },
  setup() {
    const chartOption = reactive({
      // ECharts 配置项
    });
 
    return {
      chartOption
    };
  }
});
</script>确保你已经安装了ECharts,并在你的Vue项目中正确引入。这个封装的ECharts组件接受一个option prop,它是ECharts图表的配置对象。该组件还接受id、width和height props,以便你可以自定义图表的容器ID、宽度和高度。当option prop变化时,图表会更新显示新的配置。
评论已关闭