barChart.vue 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <template>
  2. <div ref="chartDom" class="line-chart"></div>
  3. </template>
  4. <script setup>
  5. import { onMounted, ref, watch } from "vue";
  6. import * as echarts from "echarts";
  7. import { barOption } from "./chartOption.js";
  8. import { deepClone } from "@/common/commonFun";
  9. const props = defineProps({
  10. chartData: {
  11. type: Object,
  12. default: () => ({
  13. categories: [],
  14. values: [],
  15. }),
  16. },
  17. yAxisFormatter: {
  18. type: String,
  19. default: "{value}%", // 默认百分比格式
  20. },
  21. });
  22. const chartDom = ref(null);
  23. let myChart = null;
  24. const initData = () => {
  25. const newOption = deepClone(barOption);
  26. // 如果有传入数据,使用传入的数据
  27. if (props.chartData && props.chartData.categories && props.chartData.categories.length > 0) {
  28. newOption.xAxis.data = props.chartData.categories;
  29. newOption.series[0].data = props.chartData.values;
  30. }
  31. // 更新 yAxis 的 formatter
  32. newOption.yAxis.axisLabel.formatter = props.yAxisFormatter;
  33. myChart.setOption(newOption);
  34. };
  35. // 监听数据变化,更新图表
  36. watch(
  37. () => [props.chartData, props.yAxisFormatter],
  38. () => {
  39. if (myChart) {
  40. initData();
  41. }
  42. },
  43. { deep: true }
  44. );
  45. onMounted(() => {
  46. myChart = echarts.init(chartDom.value);
  47. initData();
  48. });
  49. </script>
  50. <style lang="scss" scoped>
  51. .line-chart {
  52. width: 100%;
  53. height: 100%;
  54. }
  55. </style>