<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
最新推荐文章于 2024-10-18 15:58:53 发布