BarChart.vue 2.2 KB

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