Bar.vue 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <template>
  2. <div ref="chartRef" :style="{ height, width }"></div>
  3. </template>
  4. <script lang="ts">
  5. import { defineComponent, PropType, ref, Ref, reactive, watchEffect } from 'vue';
  6. import { useECharts } from '/@/hooks/web/useECharts';
  7. export default defineComponent({
  8. name: 'bar',
  9. props: {
  10. chartData: {
  11. type: Array,
  12. default: () => [],
  13. },
  14. option: {
  15. type: Object,
  16. default: () => ({}),
  17. },
  18. xAxisPropType: {
  19. type: String,
  20. required: true,
  21. },
  22. seriesPropType: {
  23. type: String,
  24. required: true,
  25. },
  26. width: {
  27. type: String as PropType<string>,
  28. default: '100%',
  29. },
  30. height: {
  31. type: String as PropType<string>,
  32. default: 'calc(100vh - 78px)',
  33. },
  34. },
  35. setup(props) {
  36. const chartRef = ref<HTMLDivElement | null>(null);
  37. const { setOptions, echarts } = useECharts(chartRef as Ref<HTMLDivElement>);
  38. const option = reactive({
  39. tooltip: {
  40. trigger: 'axis',
  41. axisPointer: {
  42. type: 'shadow',
  43. label: {
  44. show: true,
  45. backgroundColor: '#333',
  46. },
  47. },
  48. },
  49. grid: {
  50. left: 60,
  51. right: 50,
  52. bottom: 50,
  53. },
  54. xAxis: {
  55. type: 'category',
  56. data: [],
  57. },
  58. yAxis: {
  59. type: 'value',
  60. nameTextStyle: {
  61. fontSize: 14,
  62. },
  63. },
  64. series: [
  65. {
  66. name: 'bar',
  67. type: 'bar',
  68. showBackground: true,
  69. backgroundStyle: {
  70. color: 'rgba(220, 220, 220, 0.8)',
  71. },
  72. data: [],
  73. },
  74. ],
  75. });
  76. watchEffect(() => {
  77. props.chartData && initCharts();
  78. });
  79. function initCharts() {
  80. if (props.option) {
  81. Object.assign(option, props.option);
  82. }
  83. let seriesData = props.chartData.map((item: any) => {
  84. // return item.value;
  85. return item[props.seriesPropType];
  86. });
  87. let xAxisData = props.chartData.map((item: any) => {
  88. // return item.name;
  89. return item[props.xAxisPropType];
  90. });
  91. option.series[0].data = seriesData;
  92. option.xAxis.data = xAxisData;
  93. setOptions(option, false);
  94. }
  95. return { chartRef };
  96. },
  97. });
  98. </script>