BarLabelRotation.vue 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. <template>
  2. <echartsBase :option="setOption"/>
  3. </template>
  4. <script setup>
  5. import echartsBase from './index.vue'
  6. import { nextTick, onMounted, ref, watch } from 'vue'
  7. const props = defineProps({
  8. color: {
  9. type: Array,
  10. default: () => ([])
  11. },
  12. unit: {
  13. type: String,
  14. default: ''
  15. },
  16. datas: {
  17. type: Array,
  18. default: () => ([])
  19. },
  20. lables: {
  21. type: Array,
  22. default: () => ([])
  23. },
  24. isMonth: {
  25. type: Boolean,
  26. default: false
  27. },
  28. })
  29. //初始变量
  30. const setOption = ref({})
  31. const colors = ref(props.color)
  32. const units = ref(props.unit)
  33. const datas = ref(props.datas)
  34. const isMonths = ref(props.isMonth)
  35. const xAxis = ref(props.lables)
  36. watch(() => [
  37. props.color,
  38. props.unit,
  39. props.isMonth,
  40. props.lables
  41. ], ([color, unit, isMonth, lables]) => {
  42. colors.value = color
  43. units.value = unit
  44. isMonths.value = isMonth
  45. xAxis.value = lables
  46. setOptions()
  47. })
  48. //深度监听数据变化
  49. watch(() => [
  50. props.datas,
  51. ], ([data]) => {
  52. datas.value = data
  53. setDataFormat()
  54. }, { deep: true })
  55. //处理数据
  56. const setDataFormat = () => {
  57. let series = [], lables = [], data = datas.value;
  58. if (isMonths.value) {
  59. for (let i = 1; i < 13; i++) {
  60. lables = [...lables, i + '月']
  61. }
  62. } else {
  63. lables = xAxis.value
  64. }
  65. let isLables = lables.length > 0
  66. //处理数据
  67. for (let i = 0; i < data.length; i++) {
  68. if (data[i].name) {
  69. if (!isLables) {
  70. lables.push(data[i].name)
  71. }
  72. series.push({
  73. name: data[i].name,
  74. type: 'bar',
  75. data: data[i].value
  76. })
  77. }
  78. }
  79. setOptions(lables, series)
  80. }
  81. //设置图表
  82. const setOptions = (lables = [], series = []) => {
  83. setOption.value = {
  84. color: colors.value,
  85. tooltip: {
  86. trigger: 'axis',
  87. axisPointer: {
  88. type: 'shadow'
  89. }
  90. },
  91. grid: {
  92. top: '20px',
  93. left: '0',
  94. right: '4px',
  95. bottom: '0',
  96. containLabel: true
  97. },
  98. xAxis: [
  99. {
  100. type: 'category',
  101. data: lables,
  102. }
  103. ],
  104. yAxis: [{
  105. type: 'value',
  106. axisLabel: {
  107. formatter: '{value}' + units.value
  108. },
  109. }],
  110. series: series
  111. }
  112. }
  113. //渲染完成
  114. onMounted(() => {
  115. nextTick(() => {
  116. setDataFormat()
  117. })
  118. })
  119. </script>