Newer
Older
KaiFengPC / src / components / Echarts / barChart.vue
@zhangdeliang zhangdeliang on 23 May 2 KB 初始化项目
<template>
  <!-- 柱状图 -->
  <div :id="id" style="width: 100%; height: 100%"></div>
</template>
<script setup>
import { guid } from '@/utils/ruoyi';
import useUserStore from '@/store/modules/user';
const pinias = useUserStore();
const { proxy } = getCurrentInstance();
const id = guid();
const myChart = shallowRef('');
const props = defineProps({
  //刷新标志
  refresh: {
    type: [String, Number],
    default: 1,
  },
  //数据
  echartData: {
    type: Object,
    default: {},
  },
  //标题
  title: {
    type: String,
    default: '',
  },
  //X轴type
  xAxisType: {
    type: String,
    default: 'category',
  },
  //Y轴type
  yAxisType: {
    type: String,
    default: 'value',
  },
  //是否堆叠
  stack: {
    type: String,
    default: '',
  },
  //图列的排列方式
  legend: {
    type: Object,
    default: {
      top: '2%',
      orient: 'horizontal', //horizontal
      left: 'center', //left ,center
      textStyle: {
        color: 'inherit',
      },
    },
  },
  //Y轴标题名称
  yAxisName: {
    type: String,
    default: '',
  },
  //X轴标题
  xAxisName: {
    type: String,
    default: '',
  },
});

watch(
  () => props.refresh,
  value => {
    //先销毁实例
    myChart.value && myChart.value.dispose();
    intChart();
  }
);

//自适应
function resizeTheChart() {
  if (myChart.value) {
    myChart.value.resize();
  }
}
//初始化
function intChart() {
  myChart.value = proxy.echarts.init(document.getElementById(id));
  myChart.value.clear();
  // 绘制图表
  myChart.value.setOption({
    color: pinias.$state.chartColor,
    title: { text: props.title },
    tooltip: {
      trigger: 'axis',
      showDelay: 0, // 显示延迟,添加显示延迟可以避免频繁切换,单位ms
      axisPointer: {
        // 坐标轴指示器,坐标轴触发有效
        type: 'shadow', // 默认为直线,可选为:'line' | 'shadow'
      },
    },
    grid: {
      left: '3%',
      right: '7%',
      top: '20%',
      bottom: '3%',
      containLabel: true,
    },
    legend: props.legend,
    xAxis: {
      type: props.xAxisType,
      boundaryGap: [0, 0.01],
      data: props.echartData.xAxisData,
      name: props.xAxisName,
      axisLabel: {
        color: '#c6c6c6',
      },
      axisLine: {
        lineStyle: {
          color: '#066592',
        },
      },
    },
    yAxis: {
      type: props.yAxisType,
      data: props.echartData.yAxisData,
      name: props.yAxisName,
      nameTextStyle: {
        color: '#c6c6c6',
        fontSize: 12,
      },
      axisLabel: {
        color: '#c6c6c6', //字体颜色
        fontSize: 12, //字体大小
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#066592',
        },
      },
    },
    series: props.echartData.seriesData,
  });
}
onMounted(() => {
  intChart();
  window.addEventListener('resize', resizeTheChart);
});
</script>