欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于vue封装的公共的图表组件Echarts

程序员文章站 2024-01-25 20:18:52
...

1、安装echarts依赖
npm install echarts -S
2、

<template>
  <div class="default-chart"
    :style="{height:echart.height,width:echart.width}"></div>
</template>
 
<script>
import Echarts from 'echarts'
export default {
  data () {
    return {
      myChart: {},
    }
  },
  watch: {
    // 监视传入的 option 参数,如果有变化则重新设置配置项
    option: {
      handler (val) {
        this.setOption(val);
      },
      deep: true
    }
  },
  props: {
    echart: {
      type: Object,
      default:  () => ({})
    },
    renderer: {
      type: String,
      required: false
    },
    option: {
      type: Object,
      default: () => ({})
    },
    notMerge: {
      type: Boolean,
      default: false
    },
    lazyUpdate: {
      type: Boolean,
      default: false
    }

  },
  mounted () {
    this.$nextTick(function () {
      this.initChart(this.$el);
      this.setOption(this.option);
      window.addEventListener('resize', this.resize);
    });
  },
  methods: {
    // 初始化图表
    initChart (el) {
      // renderer 用于配置渲染方式 可以是 svg 或者 canvas
      const renderer = this.renderer || 'canvas';
      this.chart = Echarts.init(el, null, {
        renderer,
        width: 'auto',
        height: 'auto'
      });
    },
    // 设置配置项
    setOption (option) {
      if (!this.chart) {
        return;
      }
      const notMerge = this.notMerge;
      const lazyUpdate = this.lazyUpdate;

      this.chart.setOption(option, notMerge, lazyUpdate);
    },
    // 销毁
    dispose () {
      if (!this.chart) {
        return;
      }

      this.chart.dispose();
      this.chart = null;
    },
    // 重新渲染
    resize () {
      this.chart && this.chart.resize();
    }
  },
  beforeDestroy () {
    this.dispose();
  },
}
</script>
 
<style lang="less" scope>
</style>