BarChart.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. <template>
  2. <div id="bar-chart" ref="barChart" class="chart" :style="{ height: props.height }"></div>
  3. </template>
  4. <script setup lang="ts">
  5. import * as echarts from 'echarts/core';
  6. import {
  7. TooltipComponent,
  8. TooltipComponentOption,
  9. GridComponent,
  10. GridComponentOption,
  11. DataZoomComponent,
  12. DataZoomComponentOption,
  13. } from 'echarts/components';
  14. import { BarChart, BarSeriesOption } from 'echarts/charts';
  15. import { CanvasRenderer } from 'echarts/renderers';
  16. import { onMounted, watch } from 'vue';
  17. echarts.use([TooltipComponent, GridComponent, BarChart, CanvasRenderer, DataZoomComponent]);
  18. type EChartsOption = echarts.ComposeOption<
  19. TooltipComponentOption | GridComponentOption | BarSeriesOption | DataZoomComponentOption
  20. >;
  21. const props = withDefaults(
  22. defineProps<{
  23. chartData: number[];
  24. chartLable: string[];
  25. height?: string;
  26. }>(),
  27. {
  28. height: '372px',
  29. },
  30. );
  31. onMounted(() => {
  32. const bar: echarts.ECharts = echarts.init(document.getElementById('bar-chart')!);
  33. initBarChart(bar);
  34. watch(
  35. () => props.chartData,
  36. () => {
  37. drawBarChart(bar);
  38. },
  39. // {
  40. // deep: true,
  41. // }
  42. );
  43. });
  44. const initBarChart = (bar: echarts.ECharts) => {
  45. const barOption: EChartsOption = {
  46. tooltip: {
  47. trigger: 'axis',
  48. axisPointer: {
  49. type: 'shadow',
  50. },
  51. },
  52. grid: {
  53. left: '3%',
  54. right: '4%',
  55. bottom: '3%',
  56. containLabel: true,
  57. },
  58. dataZoom: [
  59. {
  60. startValue: 0,
  61. endValue: 13,
  62. type: 'inside',
  63. },
  64. ],
  65. xAxis: [
  66. {
  67. type: 'category',
  68. data: props.chartLable,
  69. axisTick: {
  70. alignWithLabel: true,
  71. },
  72. },
  73. ],
  74. yAxis: [
  75. {
  76. name: '访问次数',
  77. type: 'value',
  78. },
  79. ],
  80. series: [
  81. {
  82. // name: props.chartCategory,
  83. type: 'bar',
  84. barWidth: '60%',
  85. data: props.chartData,
  86. },
  87. ],
  88. };
  89. bar.setOption(barOption);
  90. };
  91. const drawBarChart = (bar: echarts.ECharts) => {
  92. const barOption: EChartsOption = {
  93. xAxis: [
  94. {
  95. data: props.chartLable,
  96. },
  97. ],
  98. series: [
  99. {
  100. data: props.chartData,
  101. },
  102. ],
  103. };
  104. bar.setOption(barOption);
  105. };
  106. </script>
  107. <style scoped lang="scss">
  108. #bar-chart {
  109. width: 968px;
  110. }
  111. </style>