Practice of Vue Realizing Width and Height Adaptation of Echarts Chart

  • 2021-12-05 05:24:09
  • OfStack

Directory 1. Install and import 2. Define an anti-shake function 3. Draw chart code init method
resize method official website explanation

1. Install and introduce


npm install echarts --save

//main.js 

// import echarts from 'echarts'; 
import * as echarts from 'echarts'; //  If you are installing echarts 5 The above version needs to be introduced in this way 
Vue.prototype.$echarts = echarts

2. Define an anti-shake function

Portal: anti-shake, throttling and application scenarios of functions implemented in Vue


// utils/common.js

//  Anti-shake 
function _debounce(fn, delay = 300) {
  var timer = null;
  return function () {
    var _this = this;
    var args = arguments;
    if (timer) clearTimeout(timer); 
    timer = setTimeout(function () {
      fn.apply(_this, args);
    }, delay);
  };
}

export{
  _debounce,
}

3. Draw chart code


<template>
  <div class="charts">
    <div id="lineChart" :style="{ width: '100%', height: '400px' }"></div>
  </div>
</template>

<script>
import { _debounce } from '@/utils/common.js'
export default {
  data() {
    return {};
  },
  methods: {
    drawLine() {
      //  Based on the prepared dom , initialize echarts Instances 
      let lineChart = this.$echarts.init(document.getElementById("lineChart"));
      lineChart.setOption({
        title: {
          text: " Rainfall flow diagram ",
          x: "center",
        },
        xAxis: {
          type: "category",
          data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        yAxis: {
          type: "value",
        },
        series: [
          {
            data: [820, 932, 901, 934, 1290, 1330, 1320],
            type: "line",
          },
        ],
      });
    },
    resizeCharts:_debounce(function(){
      this.$echarts.init(document.getElementById('lineChart')).resize()
    },500)
  },
  mounted() {
    this.drawLine();
    window.addEventListener('resize',this.resizeCharts);
  },
  beforeDestroy () {
    window.addEventListener('resize',this.resizeCharts);
  },
};
</script>

init method

Creates 1 ECharts instance and returns echartsInstance. Multiple ECharts instances cannot be initialized on a single container.


(dom: HTMLDivElement|HTMLCanvasElement, theme?: Object|string, opts?: {
    devicePixelRatio?: number,
    renderer?: string,
    useDirtyRect?: boolean, //  From  `v5.0.0`  Begin support 
    width?: number|string,
    height?: number|string,
    locale?: string
}) => ECharts

dom: Instance container, 1 is generally an div element with high width.

Note: If div is hidden, ECharts may fail to obtain the width and height of div, so you can explicitly specify style. width and style. height of div, or manually call echartsInstance. resize to resize after div is displayed.

ECharts 3 supports direct use of canvas elements as containers, so that canvas can be directly applied to other places as pictures after drawing charts. For example, as a map in WebGL, this supports real-time refresh of charts compared to using echartsInstance. getDataURL to generate picture links.

theme: The subject of the application. It can be a configuration object for 1 topic, or it can be a topic name that has been registered through echarts. registerTheme.

opts: Additional parameters. There are several options:

devicePixelRatio device pixel ratio, default to the browser value window. devicePixelRatio. renderer renderer with support for 'canvas' or 'svg'. See rendering using Canvas or SVG. Whether useDirtyRect turns on dirty rectangle rendering, defaults to false. See ECharts 5 New Features. width explicitly specifies the instance width in pixels. If the passed-in value is null/undefined/' auto ', the width of dom (instance container) is automatically taken. height explicitly specifies the instance height in pixels. If the passed-in value is null/undefined/' auto ', the height of dom (instance container) is automatically taken. The language used by locale includes' ZH 'and' EN '. You can also register new language packs using the echarts. registerLocale method. See src/i18n for the currently supported languages.

If you do not specify a subject, you also need to pass null before passing opts, such as: const chart = echarts. init (dom, null, {renderer: 'svg'});

resize method official website explanation

Change the chart size, which needs to be called manually when the container size changes.


(opts?: {
    width?: number|string,
    height?: number|string,
    silent?: boolean,
    animation?: {
        duration?: number
        easing?: string
    }
}) => ECharts

Parameters:

opts can be the default. There are several options:

width: Instance width can be explicitly specified in pixels. If the passed-in value is null/undefined/'auto', the width of dom (instance container) is automatically taken. height: Instance height can be explicitly specified in pixels. If the value passed in is null/undefined/'auto', the height of dom (instance container) is automatically taken. silent: Whether to disable throwing events. The default is false. animation: Whether transition animation is applied when resize includes two configurations: duration duration and slow motion easing. The default duration is 0, that is, transition animation is not applied.

Hint:
Sometimes charts are placed in multiple tabs, and those initially hidden tabs may fail to draw when initializing charts because they cannot get the actual height and width of containers. Therefore, when switching to this tab, you need to manually call resize method to get the correct height and width and refresh the canvas, or display the specified chart height and width in opts.
Portal: Echarts Official Document


Related articles: