BarLabelChart.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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: () => (['#5087EC', '#68BBC4'])
  11. },
  12. unit: {
  13. type: String,
  14. default: '元'
  15. },
  16. datas: {
  17. type: Array,
  18. default: () => ([])
  19. },
  20. })
  21. //初始变量
  22. const setOption = ref({})
  23. const colors = ref(props.color)
  24. const units = ref(props.unit)
  25. const datas = ref(props.datas)
  26. watch(() => [
  27. props.color,
  28. props.unit,
  29. ], ([color, unit]) => {
  30. colors.value = color
  31. units.value = unit
  32. setOptions()
  33. })
  34. //深度监听数据变化
  35. watch(() => [
  36. props.datas,
  37. ], ([data]) => {
  38. datas.value = data
  39. setDataFormat()
  40. }, { deep: true })
  41. //处理数据
  42. const setDataFormat = () => {
  43. let series = [], lables = [], data = datas.value;
  44. //处理数据
  45. for (let i = 0; i < data.length; i++) {
  46. if (data[i].name) {
  47. lables.push(data[i].name)
  48. series.push(data[i].value)
  49. }
  50. }
  51. setOptions(lables, series)
  52. }
  53. //设置图表
  54. const setOptions = (lables = [], series = []) => {
  55. setOption.value = {
  56. tooltip: {
  57. trigger: 'axis',
  58. axisPointer: {
  59. type: 'shadow'
  60. }
  61. },
  62. grid: {
  63. top: '20px',
  64. left: '0',
  65. right: '4px',
  66. bottom: '0',
  67. containLabel: true
  68. },
  69. xAxis: [
  70. {
  71. type: 'category',
  72. data: lables,
  73. }
  74. ],
  75. yAxis: [{
  76. type: 'value',
  77. axisLabel: {
  78. formatter: '{value}' + units.value
  79. },
  80. }],
  81. series: [
  82. {
  83. data: series,
  84. type: 'bar',
  85. showBackground: true,
  86. backgroundStyle: {
  87. color: 'rgba(180, 180, 180, 0.2)'
  88. }
  89. }
  90. ]
  91. }
  92. }
  93. //渲染完成
  94. onMounted(() => {
  95. nextTick(() => {
  96. setDataFormat()
  97. })
  98. })
  99. </script>