Vue echarts

2019-10-14  本文已影响0人  阿文灬

安装 echarts

npm install echarts --save

图表组件

如果经常使用图表,则可以封装一个 图表组件,并提供一个 对应echarts图表的 option 属性。
考虑到,图表渲染的 dom元素 宽高变化需要重新 resize()。这里再安装一下 resize-detector

npm i --save resize-detector

resize-detector 能跟踪DOM树和渲染树中的分离/附着。
注意 resize-detectorES ModuleCommonJS 格式发布的,以及当您使用Webpack 捆绑您的应用程序时,ESM 版本将被导入。它不会被Babel或类似工具进行转译,因此您必须在构建过程中进行转译。
对于带有 babe-loaderwebpack,您需要将其添加到 include 选项字段中:

{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [
    // other stuff to be transpiled
    // ...
    path.resolve('node_modules/resize-detector')
  ]
}

实现组件主要思路

// chart.vue

<template>
  <div ref="chartDom"></div>
</template>

<script>
import echarts from 'echarts';
import debounce from 'lodash/debounce';
import { addListener, removeListener } from 'resize-detector';

export default {
  props: {
    option: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    // 这里没有使用深度监测,所以使用该组件时,得重新传一个 option 对象
    option(val) {
      this.chart.setOption(val, true);
    }
  },
  created() {
    // 防抖
    this.resize = debounce(this.resize, 300);
  },
  mounted() {
    this.renderChart();
    addListener(this.$refs.chartDom, this.resize);
  },
  beforeDestroy() {
    removeListener(this.$refs.chartDom, this.resize);
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    resize() {
      this.chart.resize();
    },
    renderChart() {
      this.chart = echarts.init(this.$refs.chartDom);
      this.chart.setOption(this.option);
    }
  }
};
</script>

// chart-demo.vue

<template>
  <div>
    <chart class="chart" :option="option"></chart>
  </div>
</template>

<script>
import Chart from '../../components/chart';

export default {
  components: {
    Chart
  },
  data() {
    return {
      option: {
        xAxis: {
          type: 'category',
          data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: [120, 200, 150, 80, 70, 110, 130],
            type: 'bar'
          }
        ]
      }
    };
  }
};
</script>

<style lang="scss" scoped>
.chart {
  width: 400px;
  height: 300px;
}
</style>
chart-demo.png
上一篇 下一篇

猜你喜欢

热点阅读