BarChart.vue 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <template>
  2. <div class="BarChart-box">
  3. <div ref="echart" class="BarChart-echarts" :style="`width : ${chart?.clientWidth}px`"/>
  4. </div>
  5. </template>
  6. <script setup>
  7. import * as echarts from 'echarts'
  8. import { nextTick, onMounted, onUnmounted, ref } from 'vue'
  9. //初始变量
  10. let chart = null;
  11. const echart = ref(null)
  12. //初始化图表
  13. const initChart = () => {
  14. chart = echarts.init(echart.value)
  15. setOptions()
  16. }
  17. //监听浏览器窗口变化
  18. const windowResize = () => {
  19. window.addEventListener("resize", resizeEvent);
  20. }
  21. const resizeEvent = () => {
  22. window.requestAnimationFrame(() => {
  23. chart.resize();
  24. })
  25. }
  26. //设置图表
  27. const setOptions = () => {
  28. chart.setOption({
  29. color: ['#4094C2', '#6DC8E1'],
  30. tooltip: {
  31. trigger: 'axis',
  32. axisPointer: {
  33. type: 'shadow'
  34. }
  35. },
  36. legend: {
  37. data: ['内业', '外业']
  38. },
  39. xAxis: [
  40. {
  41. type: 'category',
  42. data: ['名称1', '名称2', '名称3', '名称4', '名称5', '名称6', '名称7'],
  43. axisLabel: { interval: 0, rotate: 30 }
  44. }
  45. ],
  46. yAxis: [
  47. {
  48. type: 'value',
  49. interval: 30,
  50. axisLabel: {
  51. formatter: '{value}%'
  52. }
  53. }
  54. ],
  55. series: [
  56. {
  57. name: '内业',
  58. type: 'bar',
  59. stack: '名称1',
  60. data: [320, 332, 301, 334, 390, 330, 320],
  61. tooltip: {
  62. valueFormatter(value) {
  63. return value + '%';
  64. }
  65. },
  66. },
  67. {
  68. name: '外业',
  69. type: 'bar',
  70. stack: '名称1',
  71. data: [120, 132, 101, 134, 90, 230, 210],
  72. tooltip: {
  73. valueFormatter(value) {
  74. return value + '%';
  75. }
  76. },
  77. }
  78. ],
  79. })
  80. }
  81. //渲染完成
  82. onMounted(() => {
  83. nextTick(() => {
  84. initChart()
  85. windowResize()
  86. })
  87. })
  88. //被卸载
  89. onUnmounted(() => {
  90. window.removeEventListener("resize",resizeEvent);
  91. chart.dispose()
  92. chart = null
  93. })
  94. </script>
  95. <style lang="scss" scoped>
  96. .BarChart-box {
  97. height: 100%;
  98. overflow: hidden;
  99. position: relative;
  100. .BarChart-echarts {
  101. position: absolute;
  102. bottom: 0;
  103. left: 0;
  104. right: 0;
  105. z-index: 2;
  106. width: 100%;
  107. height: 100%;
  108. }
  109. }
  110. </style>