简单的echarts封装,

<template>
  <div :id="id" class="e_box"></div>
</template>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
const props = defineProps({
  lineData: {
    type: Array,
    default: () => [
      {
        name: '这是默认名称',
        data: [1, 2, 3, 4, 5, 6, 7]
      }
    ]
  },
  XAxis: {
    type: Array,
    default: () => [1, 2, 3, 4, 5, 6, 7]
  },
  xAxisUnit: {
    type: String,
    default: '天'
  },
  yAxisUnit: {
    type: String,
    default: '个'
  }
});
// 核心是动态创建唯一id,父组件多个图表时,浏览不会报错
const num = Math.random().toString(36).slice(2, 10);
const id = `baseChart${num}`;
const Dom = ref(null);

const showChartsFn = () => {
  const dom = document.getElementById(id);
  if (!dom) return;
  Dom.value = echarts.init(dom);
  setOption();
};
const setOption = () => {
  const series = [];
  props.lineData.forEach(item => {
    series.push({
      data: item.data,
      type: 'line',
      name: item.name,
      connectNulls: true
    });
  });
  const option = {
    tooltip: {
      trigger: 'axis',
      confine: true
    },
    legend: {
      data: props.lineData.map(item => item.name)
    },
    xAxis: {
      type: 'category',
      data: props.XAxis,
      name: props.xAxisUnit
    },
    yAxis: {
      type: 'value',
      name: props.yAxisUnit
    },
    series
  };
  Dom.value.setOption(option, true);
};
watch(
  () => props.lineData,
  val => {
    if (Dom.value && val) {
      setOption();
    }
  },
  {
    deep: true
  }
);
onMounted(() => {
  showChartsFn();
});
posted @ 2023-03-09 10:51  Life_countdown  阅读(43)  评论(0)    收藏  举报