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