Practice of realizing Echarts chart width and height adaptation in Vue

Practice of realizing Echarts chart width and height adaptation in Vue

1. Install and import

npm install echarts --save
//main.js 

// import echarts from 'echarts'; 
import * as echarts from 'echarts'; // If you install echarts 5 or above, you need to import it in this way Vue.prototype.$echarts = echarts

2. Define the anti-shake function

Portal: Implementing anti-shake, throttling and application scenarios of functions 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() {
      // Initialize the echarts instance based on the prepared dom let lineChart = this.$echarts.init(document.getElementById("lineChart"));
      lineChart.setOption({
        title:
          text: "Rainfall and flow relationship 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

Create an ECharts instance and return echartsInstance. You cannot initialize multiple ECharts instances on a single container.

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

dom: instance container, usually a div element with height and width.

Note: If the div is hidden, ECharts may not be able to obtain the height and width of the div, resulting in initialization failure. In this case, you can explicitly specify the style.width and style.height of the div, or manually call echartsInstance.resize to adjust the size after the div is displayed.

ECharts 3 supports using canvas elements directly as containers, so that after drawing the chart, the canvas can be directly applied to other places as an image. For example, in WebGL as a texture, this can support real-time refresh of the chart compared to using echartsInstance.getDataURL to generate an image link.

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

opts: additional parameters. There are several options:

  • devicePixelRatio device pixel ratio, the default value is the browser window.devicePixelRatio.
  • renderer Renderer, supports 'canvas' or 'svg'. See Rendering with Canvas or SVG.
  • useDirtyRect Whether to enable dirty rectangle rendering, the default value is false. See ECharts 5 New Features.
  • width can be used to explicitly specify the instance width in pixels. If the input value is null/undefined/'auto', it means that the width of the DOM (instance container) is automatically taken.
  • height You can explicitly specify the instance height in pixels. If the passed value is null/undefined/'auto', it means that the height of the DOM (instance container) is automatically taken.
  • The language used by locale, there are two built-in languages ​​'ZH' and 'EN', you can also use echarts.registerLocale method to register a new language pack. See src/i18n for currently supported languages.

If you do not specify a theme, 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. This function 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

parameter:

opts can be omitted. There are several options:

  • width: You can explicitly specify the instance width in pixels. If the input value is null/undefined/'auto', it means that the width of the DOM (instance container) is automatically taken.
  • height: You can explicitly specify the instance height in pixels. If the passed value is null/undefined/'auto', it means that the height of the DOM (instance container) is automatically taken.
  • silent: Whether to prohibit throwing events. The default value is false.
  • animation: Whether to apply transition animation when resizing, including duration and easing configuration. The default duration is 0, which means no transition animation is applied.

hint:
Sometimes charts are placed in multiple tabs. When initializing the chart, the initially hidden tabs may fail to draw because they cannot obtain the actual height and width of the container. Therefore, when switching to the tab, you need to manually call the resize method to obtain the correct height and width and refresh the canvas, or display the specified chart height and width in opts.
Portal: Echarts official documentation

This concludes this article about how to use Vue to implement Echarts chart width and height adaptation. For more information about Vue Echarts chart width and height adaptation, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Several solutions for vue to use echarts chart adaptation
  • Perfect solution to the problem of multiple echarts charts adaptation in vue
  • The adaptive method of echarts3.0 in vue

<<:  Essential tools for web design: Firefox Web Developer plugin CSS tool set tutorial

>>:  A brief analysis of how to use border and display attributes in CSS

Recommend

Detailed explanation of MySql slow query analysis and opening slow query log

I have also been researching MySQL performance op...

How to make form input and other text boxes read-only and non-editable in HTML

Sometimes, we want the text boxes in the form to b...

Detailed explanation of redundant and duplicate indexes in MySQL

MySQL allows you to create multiple indexes on th...

Two ways to remove the 30-second ad code from Youku video

I believe everyone has had this feeling: watching ...

Implementation of deploying war package project using Docker

To deploy war with Docker, you must use a contain...

Initial settings after installing Ubuntu 16 in the development environment

The office needs Ubuntu system as the Linux devel...

Modularity in Node.js, npm package manager explained

Table of contents The basic concept of modularity...

Vue Element-ui implements tree control node adding icon detailed explanation

Table of contents 1. Rendering 2. Bind data and a...

Tips for List Building for Website Maintenance Pages

And, many times, maintenance requires your website...

A brief discussion on docker compose writing rules

This article does not introduce anything related ...

MySQL SHOW PROCESSLIST assists in the entire process of troubleshooting

1. SHOW PROCESSLIST command SHOW PROCESSLIST show...

Linux system prohibits remote login command of root account

ps: Here is how to disable remote login of root a...