StackBar.vue 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. <template>
  2. <div ref="chartRef" :style="{ height, width }"></div>
  3. </template>
  4. <script lang="ts">
  5. import { defineComponent, PropType, ref, Ref, reactive, watchEffect, watch } from 'vue';
  6. import { useECharts } from '/@/hooks/web/useECharts';
  7. import { cloneDeep } from 'lodash-es';
  8. export default defineComponent({
  9. name: 'StackBar',
  10. props: {
  11. chartData: {
  12. type: Array,
  13. default: () => [],
  14. required: true,
  15. },
  16. size: {
  17. type: Object,
  18. default: () => {},
  19. },
  20. option: {
  21. type: Object,
  22. default: () => ({}),
  23. },
  24. type: {
  25. type: String as PropType<string>,
  26. default: 'bar',
  27. },
  28. width: {
  29. type: String as PropType<string>,
  30. default: '100%',
  31. },
  32. height: {
  33. type: String as PropType<string>,
  34. default: 'calc(100vh - 78px)',
  35. },
  36. },
  37. setup(props) {
  38. const chartRef = ref<HTMLDivElement | null>(null);
  39. const { setOptions, echarts, resize } = useECharts(chartRef as Ref<HTMLDivElement>);
  40. const option = reactive({
  41. tooltip: {
  42. trigger: 'axis',
  43. axisPointer: {
  44. type: 'shadow',
  45. label: {
  46. show: true,
  47. backgroundColor: '#333',
  48. },
  49. },
  50. },
  51. legend: {
  52. top: 30,
  53. },
  54. grid: {
  55. top: 60,
  56. },
  57. xAxis: {
  58. type: 'value',
  59. },
  60. yAxis: {
  61. type: 'category',
  62. data: [],
  63. },
  64. series: [],
  65. });
  66. watchEffect(() => {
  67. props.chartData && initCharts();
  68. });
  69. /**
  70. * 监听拖拽大小变化
  71. */
  72. watch(
  73. () => props.size,
  74. () => {
  75. console.log('props.size', props.size);
  76. resize();
  77. },
  78. {
  79. immediate: true,
  80. }
  81. );
  82. function initCharts() {
  83. if (props.option) {
  84. Object.assign(option, cloneDeep(props.option));
  85. }
  86. //图例类型
  87. let typeArr = Array.from(new Set(props.chartData.map((item) => item.type)));
  88. //轴数据
  89. let yAxisData = Array.from(new Set(props.chartData.map((item) => item.name)));
  90. let seriesData = [];
  91. typeArr.forEach((type) => {
  92. let obj = { name: type, type: props.type, stack: 'total' };
  93. let chartArr = props.chartData.filter((item) => type === item.type);
  94. //data数据
  95. obj['data'] = chartArr.map((item) => item.value);
  96. seriesData.push(obj);
  97. });
  98. option.series = seriesData;
  99. option.yAxis.data = yAxisData;
  100. setOptions(option);
  101. }
  102. return { chartRef };
  103. },
  104. });
  105. </script>