Eecharts.vue 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <template>
  2. <div ref="chartDom" style="width: 100%; height: 100%"></div>
  3. </template>
  4. <script>
  5. import * as echarts from "echarts";
  6. export default {
  7. name: "LineChart",
  8. props: {
  9. xData: {
  10. type: Array,
  11. required: true,
  12. },
  13. yData: {
  14. type: Array, // 二维数组
  15. required: true,
  16. },
  17. yNames: {
  18. type: Array,
  19. required: true, // 只取第一个元素
  20. },
  21. yAxisName: {
  22. type: String,
  23. default: "",
  24. },
  25. },
  26. data() {
  27. return {
  28. myChart: null,
  29. };
  30. },
  31. mounted() {
  32. this.initChart();
  33. },
  34. watch: {
  35. xData: {
  36. handler: "initChart",
  37. deep: true,
  38. immediate: true,
  39. },
  40. yData: {
  41. handler: "initChart",
  42. deep: true,
  43. immediate: true,
  44. },
  45. yNames: {
  46. handler: "initChart",
  47. immediate: true,
  48. },
  49. yAxisName: {
  50. handler: "initChart",
  51. immediate: true,
  52. },
  53. },
  54. methods: {
  55. initChart() {
  56. if (!this.$refs.chartDom) return;
  57. if (!this.myChart) {
  58. this.myChart = echarts.init(this.$refs.chartDom);
  59. }
  60. const colors = ["#02aae9", "#5470C6", "#3CB9B9", "#9966CC"]; // 颜色列表可以根据需要扩展
  61. const series = this.yData.map((data, index) => ({
  62. name: this.yNames[index] || `系列${index + 1}`,
  63. type: "line",
  64. data: data,
  65. lineStyle: {
  66. color: colors[index % colors.length],
  67. },
  68. itemStyle: {
  69. color: colors[index % colors.length],
  70. },
  71. }));
  72. const option = {
  73. tooltip: {
  74. trigger: "axis",
  75. },
  76. legend: {
  77. data: this.yNames.slice(0, series.length),
  78. top: 10,
  79. },
  80. grid: {
  81. top: 40,
  82. bottom: 0,
  83. left: 40,
  84. right: 20,
  85. containLabel: true,
  86. },
  87. xAxis: {
  88. type: "category",
  89. data: this.xData,
  90. },
  91. yAxis: {
  92. type: "value",
  93. name: this.yAxisName,
  94. },
  95. series: series,
  96. color: colors,
  97. };
  98. this.myChart.clear(); // ✅ 清除旧配置
  99. this.myChart.setOption(option);
  100. },
  101. },
  102. };
  103. </script>
  104. <style scoped>
  105. </style>