<template>
<div class="chart-container" ref="chartContainer"></div>
</template>
<script>
import echarts from 'echarts';
export default {
name: 'CommonCharts',
props: {
// 图表配置
chartOptions: {
type: Object,
default() {
return {};
}
},
/**
* 图表配置
* @param {string} name - 城市名称拼音
* @param {JSON} geoData - 城市的geo JSON 数据
* @returns {Object} {name:'guiyang',geoData:JSON data}
*/
mapCityOption: {
type: Object,
default() {
return {};
}
}
},
data() {
return {
chart: null
};
},
mounted() {
this.chart = echarts.init(this.$refs.chartContainer);
// 注册地图数据
this.mapCityOption && echarts.registerMap(this.mapCityOption.name, this.mapCityOption.geoData);
this.chart.setOption(this.chartOptions);
this.handleResize(); // 设置初始大小
// 监听父容器大小变化,自适应图表大小
window.addEventListener('resize', this.handleResize);
},
methods: {
update() {
this.chart.setOption(this.chartOptions);
},
// 更新图表大小
handleResize() {
const container = this.$refs.chartContainer;
const width = container.offsetWidth;
const height = container.offsetHeight;
this.chart.resize({width, height});
this.$forceUpdate();
}
},
beforeDestroy() {
window.removeEventListener('resize', this.handleResize);
if (this.chart) {
this.chart.dispose();
this.chart = null;
}
}
};
</script>
<style scoped>
.chart-container {
width: 100%;
height: 100%;
}
</style>
【vue】封装echart公共组件2023
使用Echarts初始化地图图表组件
最新推荐文章于 2025-11-24 03:02:26 发布
该代码段展示了一个基于Vue的Echarts组件,用于创建和管理图表。组件在挂载时初始化Echarts实例,接收图表配置和地图城市数据,注册地图并设置图表选项。同时,它处理窗口大小变化以实现图表的自适应布局,并在销毁时清理资源。
1058

被折叠的 条评论
为什么被折叠?



