【vue】封装echart公共组件2023

<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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值