“This is the fifth day of my participation in the First Challenge 2022. For details: First Challenge 2022.”

1. How to use ECharts in Vue

1.1. Installation ECharts

npm install echarts --save
Copy the code

1.2 introduce the ECharts

Import all globally in vue project main.js:

Prototype.$echarts = echarts.$echarts = echartsCopy the code

The above import method is to import all the diagrams and components in ECharts, which will cause the file to be too large when packaging, so we can also import them as needed in the.vue file where we need to draw:

// Introduce the Echarts core module, which provides the interface required for echarts use. Import * as echarts from 'echarts/core' Import {BarChart, PieChart, LineChart} from 'echarts/charts' // Import tooltips, titles, cartes components, Component import {TitleComponent, TooltipComponent, GridComponent, LegendComponent, DatasetComponent} from 'echarts/ Components' {CanvasRenderer} from 'echarts/renderers' import {CanvasRenderer} from 'echarts/renderers' // Register required components echarts.use([ TitleComponent, TooltipComponent, GridComponent, BarChart, PieChart, LineChart, CanvasRenderer, LegendComponent, DatasetComponent ])Copy the code

1.3. Draw with ECharts

Create a new fixed-width div with an ID (required) main in the page tag

<template> <div class="app-container"> <div id="main" style="width:800px; height:700px" /> </div> </template>Copy the code

Write drawing methods in methods, which contain configuration information for some diagrams

methods: { initChart(domName, title) { var myChart = this.$echarts.init(domName) var option = { title: { text: The title}, legend: {data: [' sales']}, xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, the series: [{name: 'sales ', type: 'bar', data: [5, 20, 36, 10, 10, 20]}]} option && mychart.setoption (option)}}Copy the code

Call this method in Mounted to draw a picture

mounted() {
   this.initChart(document.getElementById('main'), '111111111')
},
Copy the code

The page looks like this

The above is the basic method of using ECharts drawing in VUE, the specific can also refer to the official.

However, the basic use of light often fails to meet the needs of the project. Generally, in the project, we need to achieve adaptive graph or multi-graph, nested graph, real-time data graph, circular graph and so on. Let’s first study how to achieve adaptive chart.

2.ECharts chart adaptation

2.1. If

Set the width and height of the chart container to a percentage as follows:

<template> <div class="app-container"> <div class="chartCon"> <div class="normalStyle"> <div id="main1" style="width:100%; height:100%" /> </div> <div class="normalStyle"> <div id="main2" style="width:100%; height:100%" /> </div> </div> </div> </template> <script> export default { data() { return { } }, mounted() { this.initChart(document.getElementById('main1'), '111111111') this.initChart(document.getElementById('main2'), '222222222') }, methods: { initChart(domName, title) { var myChart = this.$echarts.init(domName) var option = { title: { text: title }, legend: } {data: [' sales'], xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, series: [{name: 'sales', type: 'bar', data: [5, 20, 36, 10, 10, </script> <style lang=" SCSS ">. ChartCon {width: calc(100% - 40px); background-color: #fff; position: absolute; left: 20px; right: 20px; bottom: 20px; top: 20px; .normalStyle{ width:50%; height:100%; float:left; border:1px solid #eee } } </style>Copy the code

Page rendering has the following problems:

1) When rendering for the first time, the chart height is not 100% as set, as shown below:

2) You need to manually click the refresh button of the browser to display it normally, as shown in the figure:

3) The chart does not adapt to the size of the browser window, as shown in figure:

2.2. Realize self-adaptation

Use window.onresize (official)

Based on the code in the premise, change the code for the initChart method as follows:

initChart(domName, Title) {var myChart = this.$echarts.init(domName) // Self-matching window.onresize = function() {myChart {title: {text: the title}, legend: {data: [' sales']}, xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, series: [{name: 'sales ', type: 'bar', data: [5, 20, 36, 10, 10, 20]}} // Draw graph option && mychart.setoption (option)}Copy the code

Existing problems:

1) When rendering for the first time, the chart height is still not 100% as set, as shown below:

2) It still needs to be refreshed manually for normal display, as shown in the figure:

2) When there are multiple charts, only the last adaptive will take effect, and onResize will be overwritten, as shown in the figure:

Add the resize method using window.addEventListener

Based on the code in the premise, change the code for the initChart method as follows:

initChart(domName, Var listener = function() {mychart.resize ()} var listener = function() {mychart.resize ()} Window.addeventlistener ('resize', listener) var option = {title: {text: title}, legend: {data: [' sales ']}, xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, series: [{name: 'sales' type:' bar 'data: [5, 20, 36, 10, 10, 20]}} // Draw graph option && mychart.setoption (option)}Copy the code

Existing problems:

1) When rendering for the first time, the chart height is still not 100% as set, as shown below:

2) It still needs to be refreshed manually for normal display, as shown in the figure:

3) Although the chart is basically adaptive, when the VUE page route jumps to the next page, the onresize method of the previous page will continue to execute.

Method 3: Encapsulate the adaptive method esresize

Reference: blog.csdn.net/qq_31967985…

Esresize. Js as follows:

var EleResize = { _handleResize: function(e) { var ele = e.target || e.srcElement var trigger = ele.__resizeTrigger__ if (trigger) { var handlers = trigger.__z_resizeListeners if (handlers) { var size = handlers.length for (var i = 0; i < size; i++) { var h = handlers[i] var handler = h.handler var context = h.context handler.apply(context, [e]) } } } }, _removeHandler: function(ele, handler, context) { var handlers = ele.__z_resizeListeners if (handlers) { var size = handlers.length for (var i = 0; i < size; i++) { var h = handlers[i] if (h.handler === handler && h.context === context) { handlers.splice(i, 1) return } } } }, _createResizeTrigger: function(ele) { var obj = document.createElement('object') obj.setAttribute('style', 'display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; opacity: 0; pointer-events: none; z-index: -1; ') obj.onload = EleResize._handleObjectLoad obj.type = 'text/html' ele.appendChild(obj) obj.data = 'about:blank' return obj }, _handleObjectLoad: function(evt) { this.contentDocument.defaultView.__resizeTrigger__ = this.__resizeElement__ this.contentDocument.defaultView.addEventListener('resize', EleResize._handleResize) } } if (document.attachEvent) { // ie9-10 EleResize.on = function(ele, handler, context) { var handlers = ele.__z_resizeListeners if (! handlers) { handlers = [] ele.__z_resizeListeners = handlers ele.__resizeTrigger__ = ele ele.attachEvent('onresize', EleResize._handleResize) } handlers.push({ handler: handler, context: context }) } EleResize.off = function(ele, handler, context) { var handlers = ele.__z_resizeListeners if (handlers) { EleResize._removeHandler(ele, handler, context) if (handlers.length === 0) { ele.detachEvent('onresize', EleResize._handleResize) delete ele.__z_resizeListeners } } } } else { EleResize.on = function(ele, handler, context) { var handlers = ele.__z_resizeListeners if (! handlers) { handlers = [] ele.__z_resizeListeners = handlers if (getComputedStyle(ele, null).position === 'static') { ele.style.position = 'relative' } var obj = EleResize._createResizeTrigger(ele) ele.__resizeTrigger__ = obj obj.__resizeElement__ = ele } handlers.push({ handler: handler, context: context }) } EleResize.off = function(ele, handler, context) { var handlers = ele.__z_resizeListeners if (handlers) { EleResize._removeHandler(ele, handler, context) if (handlers.length === 0) { var trigger = ele.__resizeTrigger__ if (trigger) { trigger.contentDocument.defaultView.removeEventListener('resize', EleResize._handleResize) ele.removeChild(trigger) delete ele.__resizeTrigger__ } delete ele.__z_resizeListeners } } } } export { EleResize }Copy the code

Esresie.js is introduced in vue files

Import {EleResize} from '@/utils/esresizeCopy the code

Use: Based on the code in the premise, change the code for the initChart method as follows:

initChart(domName, Var listener = function() {mychart.resize ()} var listener = function() {mychart.resize ()} Eleresize.on (domName, listener) var option = {title: {text: title}, legend: {data: [' sales ']}, xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, series: [{name: 'sales' type:' bar 'data: [5, 20, 36, 10, 10, 20]}} // Draw graph option && mychart.setoption (option)}Copy the code

All of the above problems were solved using this method.

Added 2.3.

For the problem that setting the height of the chart container to a percentage does not take effect on the first rendering (method 1 above and method 2 problem 1), You can also dynamically set the chart container size to window.innerWidth and window.innerHeight by listening to the browser window change. You can use this with adaptation, but it’s not recommended, but you can also see how to do this.

The specific code is as follows:

<template> <div class="app-container"> <div class="chartCon"> <div class="normalStyle"> <div id="main1" :style="'width:'  + normalWidth/2 + 'px; height:' + normalHeight + 'px'" /> </div> <div class="normalStyle"> <div id="main2" :style="'width:' + normalWidth/2 + 'px; height:' + normalHeight + 'px'" /> </div> </div> </div> </template> <script> export default { data() { return { ScreenHeight: window.innerHeight, screenWidth: window.innerWidth, normalHeight: window.innerHeight * 0.9, normalWidth: window. window.innerWidth } }, watch: ScreenHeight (val) {this.screenheight = val this.normalheight = ScreenHeight * 0.9}, screenWidth(val) {this.screenWidth = val this.normalWidth = this.screenWidth}}, // mounted() {this.initchart (document.getelementById ('main1')), '111111111') this.initchart (document.getelementById ('main2'), '222222222') Window.onresize = () => {return () => {window.screenheight = window.innerheight window.screenWidth = window.innerWidth this.screenHeight = window.screenHeight this.screenWidth = window.screenWidth })() } }, methods: { initChart(domName, Var listener = function() {mychart.resize ()} var listener = function() {mychart.resize ()} Window.addeventlistener ('resize', listener) var option = {title: {text: title}, legend: {data: [' sales ']}, xAxis: {data: [' shirts' and 'sweater', 'snow spins unlined upper garment,' pants', 'high heels',' socks']}, yAxis: {}, series: [{name: 'sales' type:' bar 'data: [5, 20, 36, 10, 10, </script> <style lang=" SCSS ">. ChartCon {width: calc(100% - 40px); background-color: #fff; position: absolute; left: 20px; right: 20px; bottom: 20px; top: 20px; .normalStyle{ width:50%; height:100%; float:left; border: 1px solid #eee; } } </style>Copy the code

The initial rendering of the page is intact, as shown below:

3. Summary

The above content is only for some problems and solutions when drawing in div. It seems that drawing in Tabs will cause other problems. Continue researching, thank you!