| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- <template>
- <div :id="chartId" class="chart-container"></div>
- </template>
- <script>
- import * as echarts from 'echarts';
- import 'echarts/map/js/china'; // 确保地图模块引入
- export default {
- name: 'EChartsComponent',
- props: {
- chartId: {type: String, required: true},
- option: {type: Object, required: true}
- },
- mounted() {
- this.$nextTick(() => { // 确保DOM渲染完成后初始化
- this.initChart();
- window.addEventListener('resize', this.resizeChart);
- });
- },
- // 监听 option 变化,自动更新图表
- watch: {
- option: {
- deep: true, // 深度监听对象内部变化
- handler(newVal) {
- if (this.chart) {
- this.chart.setOption(newVal); // 关键:用新数据更新图表
- }
- }
- }
- },
- beforeDestroy() {
- window.removeEventListener('resize', this.resizeChart);
- if (this.chart) this.chart.dispose();
- },
- methods: {
- initChart() {
- const container = document.getElementById(this.chartId);
- if (!container) return; // 防止容器不存在
- this.chart = echarts.init(container);
- this.chart.setOption(this.option);
- },
- resizeChart() {
- if (this.chart) this.chart.resize();
- },
- // 暴露手动更新方法(可选,用于特殊场景)
- updateOption(newOption) {
- if (this.chart) {
- this.chart.setOption(newOption);
- }
- }
- }
- };
- </script>
- <style scoped>
- .chart-container {
- width: 100%;
- height: 100%;
- }
- </style>
|