EchartsComponent.vue 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <template>
  2. <div :id="chartId" class="chart-container"></div>
  3. </template>
  4. <script>
  5. import * as echarts from 'echarts';
  6. import 'echarts/map/js/china'; // 确保地图模块引入
  7. export default {
  8. name: 'EChartsComponent',
  9. props: {
  10. chartId: {type: String, required: true},
  11. option: {type: Object, required: true}
  12. },
  13. mounted() {
  14. this.$nextTick(() => { // 确保DOM渲染完成后初始化
  15. this.initChart();
  16. window.addEventListener('resize', this.resizeChart);
  17. });
  18. },
  19. // 监听 option 变化,自动更新图表
  20. watch: {
  21. option: {
  22. deep: true, // 深度监听对象内部变化
  23. handler(newVal) {
  24. if (this.chart) {
  25. this.chart.setOption(newVal); // 关键:用新数据更新图表
  26. }
  27. }
  28. }
  29. },
  30. beforeDestroy() {
  31. window.removeEventListener('resize', this.resizeChart);
  32. if (this.chart) this.chart.dispose();
  33. },
  34. methods: {
  35. initChart() {
  36. const container = document.getElementById(this.chartId);
  37. if (!container) return; // 防止容器不存在
  38. this.chart = echarts.init(container);
  39. this.chart.setOption(this.option);
  40. },
  41. resizeChart() {
  42. if (this.chart) this.chart.resize();
  43. },
  44. // 暴露手动更新方法(可选,用于特殊场景)
  45. updateOption(newOption) {
  46. if (this.chart) {
  47. this.chart.setOption(newOption);
  48. }
  49. }
  50. }
  51. };
  52. </script>
  53. <style scoped>
  54. .chart-container {
  55. width: 100%;
  56. height: 100%;
  57. }
  58. </style>