Expansion of application development platform capabilities - integrating echarts components to achieve chart display capabilities

background

The ability to display charts is the basic capability that the platform needs to have. Currently, echarts is the best choice.
In earlier versions of charts, different chart styles required different data formats, requiring complex encapsulation to be easy to use. Baidu officials are also aware of this problem. In the echarts 4.0 version, it provides dataset attribute support and a unified data format. It has also considered encapsulating commonly used charts based on this new feature.
Later, I discovered that v-charts, an open source component produced by the Ele.me team, uniformly provides a data format that is friendly to both the front and back ends. You only need to set simple configuration items to easily generate common charts.
But v-charts stays in vue2.x version, and vue3.x has no movement at all.
The official released vue-echarts. This article introduces how to integrate with the platform from a practical perspective, including integration solutions, specific implementations, and precautions.

Technology pre-research

vue-echarts official address
https://github.com/ecomfe/vue-echarts/blob/HEAD/README.zh-Hans.md

The explanation is too simple. If you only read the information here and don’t understand the concept and configuration of echarts itself, it will be very difficult to integrate and use. It is recommended to understand the following related knowledge.

Check the echarts chart official website documentation to understand basic concepts, such as coordinate axes, legends, data sets, etc.
https://echarts.apache.org/handbook/zh/concepts/chart-size

View echarts chart official website document configuration instructions
https://echarts.apache.org/zh/option.html#legend.top

integration target

echarts provides a wide variety of charts, about 40 categories, see https://echarts.apache.org/examples/zh/index.html#chart-type-line for details .

In actual software systems, the most common and practical are three types of charts: line charts, histograms, and pie charts.
The main goal of platform integration is to realize the integration of these three types of charts. If a specific business requirement uses other types of chart styles, it can also be achieved by directly using the native echarts chart components.

Note: For enterprise applications, echarts is not the only way to achieve charting requirements. For the actual complex report requirements, especially the management cockpit, special report tools like Fanruan are often used. Chart tools and report tools have different positioning, but their functions overlap. The chart tool relies on the back-end service interface, and the front-end performs friendly display, and the data query and conversion are all completed in the application back-end; while the report function is often directly connected to the database for the development and deployment of report templates, and the data query and conversion are mainly in the report It is completed on the application side and then integrated into the application system. The actual methods and mechanisms are different.

configuration options

To consider the integration solution, first understand the current status of echarts chart components. The requirements for configuration options of these three types of charts are as follows:

pie chart

option = {
    
    
  series: [
    {
    
    
      type: 'pie',
      data: [
        {
    
    
          value: 335,
          name: '直接访问'
        },
        {
    
    
          value: 234,
          name: '联盟广告'
        },
        {
    
    
          value: 1548,
          name: '搜索引擎'
        }
      ]
    }
  ]
};

histogram

option = {
    
    
  xAxis: {
    
    
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    
    },
  series: [
    {
    
    
      type: 'bar',
      data: [23, 24, 18, 25, 27, 28, 25]
    }
  ]
};

line chart

option = {
    
    
  xAxis: {
    
       
    data: ['A', 'B', 'C']
  },
  yAxis: {
    
        
  },
  series: [
    {
    
    
      data: [120, 200, 150],
      type: 'line'
    }
  ]
};

configuration analysis

Same point

Chart type, unified in the series.type attribute

difference

The pie chart does not have the concept of x-axis and y-axis. Configure an object array in series.data, name represents the category, and value represents the value. The line chart is the same as the histogram,
based on the Cartesian coordinate system, with x-axis and y-axis, xAxis The .data class configures a one-dimensional array as the category, and the series.data configures a one-dimensional array as the value

Integration solution

Implementation Mode - Traditional Mode VS Dataset Mode

Based on the above analysis, a component can be packaged for each of the pie chart, histogram and line chart. The default settings are provided inside the component, and key attributes, such as data and option, are exposed as attributes for the caller to use.
This approach can work, but is not the best solution. In the initial background section, the evolution of echart products was mentioned. In earlier versions of charts, different chart styles required different data formats, which needed to be encapsulated for ease of use. The official is also aware of this problem, and provides dataset attribute support in echarts 4.0 version, providing a unified data format.

The advantage of using datasets mainly comes from the separation of data and configuration, so that data can be reused by multiple components. The official description is quoted below:

Dataset (dataset) is a component specially used to manage data. Although each series can set data in series.data, but since ECharts4 supports datasets, it is recommended to use datasets to manage data. Because of this, data can be reused by multiple components, and it is also convenient for the configuration style of "data and other configurations" to be separated. After all, at runtime, data is the most frequently changed, while other configurations mostly do not change.

Setting data in a series
If the data is set in a series, for example:

option = {
    
    
  xAxis: {
    
    
    type: 'category',
    data: ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie']
  },
  yAxis: {
    
    },
  series: [
    {
    
    
      type: 'bar',
      name: '2015',
      data: [89.3, 92.1, 94.4, 85.4]
    },
    {
    
    
      type: 'bar',
      name: '2016',
      data: [95.8, 89.4, 91.2, 76.9]
    },
    {
    
    
      type: 'bar',
      name: '2017',
      data: [97.7, 83.1, 92.5, 78.1]
    }
  ]

The advantage of this method is that it is suitable for certain data type customization for some special data structures (such as "tree", "graph", and super large data). But the disadvantage is that users often need to process the data first and set the data division into each series (and category axis). In addition, it is not conducive to multiple series sharing one data, and it is also not conducive to the mapping arrangement of chart types and series based on original data.
Setting the data in the dataset
and setting the data in the dataset (dataset) will have these benefits:

  • Be able to get close to the common way of thinking of data visualization: (I) provide data, (II) specify the mapping from data to vision, so as to form a chart.
  • Data and other configuration can be separated. The data is constantly changing, and other configurations are often unchanged. Separation is easy to manage separately.
  • Data can be reused by multiple series or components. For scenarios with a large amount of data, it is not necessary to create a piece of data for each series.
  • Support more commonly used data formats, such as two-dimensional arrays, object arrays, etc., to a certain extent avoid users from converting data formats.

Source: https://echarts.apache.org/handbook/zh/concepts/dataset/

The official has made it very clear about the advantages of the data set, so I won’t go into details. The advantages of choosing the data set mode are obvious.

The necessity of component encapsulation

The official vue-echarts has actually encapsulated echarts well, including providing default configurations, exposing properties, and providing events and methods.
Next, let’s discuss the necessity of secondary packaging. Does platform integration still require secondary packaging?
If you use the vue-echarts component directly, the advantage is that the quality of the component is relatively high, and it will continue to be updated in the future. The disadvantage is that you need to understand the basic concepts and configuration information of echarts, follow the specifications and requirements of echarts, and have a certain learning cost.
If it is encapsulated twice, the configuration information of echarts can be encapsulated. For example, a component is specially encapsulated for the pie chart, and an attribute data is exposed to receive the data. Other details are ignored, and the default implementation is provided by the platform. The disadvantage is that, It is of little value and significance to wrap the properties, events, and methods of the vue-echarts component in another layer.
In addition, among the packaging components that come with the vue-element-plus-admin framework, there is a secondary packaging of the vue-echarts component. When using it, you only need to enter the configuration option and height.

Considering that the official vue-echarts itself has high packaging quality, strong flexibility and scalability, it will not be packaged for the time being, and the secondary packaging will be considered in the future when there is a clearer need for packaging.
At the same time, since echart itself provides the dataset mode and data mapping function, there is no need to specifically encapsulate the vo object for front-end and back-end interaction, and the existing rest request can be reused to return the object of the entity Array, configure data mapping in echarts.

Implementation

Install

pnpm install echarts vue-echarts

Note that these two need to be installed at the same time, not just vue-echarts.

introduce

Modify the main.js file to add the introduction and initialization of echarts

// echart图表
import "echarts"
import ECharts from "vue-echarts"



// 创建实例
const setupAll = async () => {
    
    
  const app = createApp(App)// echart图表
  app.component('v-chart', ECharts)

  app.mount('#app')
}

The full import mode actually adopted here will be optimized later to realize only the charts used in the three major categories of line charts, histograms, and pie charts, reducing the volume.

use

Create a new echart directory under the modules directory of the front-end project to store sample charts, and create three typical charts below it. And use the portlet function of the platform to define.
image.png
You can configure it as your own desktop directly by dragging, as shown below
image.png

The final effect is as follows:
image.png
the following is the code implementation, pay attention to the way the data set is used,

Pie Chart: User Sources

<template>
  <v-chart :option="option" theme="auto" :autoresize="true" style="width: 100%; height: 300px" />
</template>

<script>
export default {
  data() {
    return {
      option: {
        dataset: {
          source: [
            ['数量', '来源'],
            [335, '直接访问'],
            [310, '邮件营销'],
            [234, '联盟广告'],
            [135, '视频广告'],
            [1548, '搜索引擎']
          ]
        },
        title: {
          show: false
        },
        grid: {
          top: 20,
          bottom: 0
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            // 只返回第一列数据
            return params.data[0] + '(' + params.percent + '%)'
          }
        },
        legend: {
          orient: 'horizontal',
          top: 'bottom',
          left: 'center'
        },
        series: [
          {
            type: 'pie',
            radius: '55%',
            center: ['50%', '60%'],
            encode: {
              tooltip: [0, 1],
              value: 0,
              itemName: 1
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  methods: {}
}
</script>

<style></style>

The content introduction on the official website based on the data set and data mapping is relatively scattered. In fact, you still need to try to modify the configuration yourself to confirm the function of the parameters and achieve the final effect.
Note that there are two places.
One is data mapping, as shown in the figure below. value: 0 means that column 0 in the dataset is used as data, and itemName: 1 means that column 1 in the dataset is used as a dimension. Mapping the wrong graph is likely to display incomplete or simply display a blank screen.

encode: {
  tooltip: [0, 1],
  value: 0,
  itemName: 1
}

The second is that when the mouse hovers over a certain area, it will float to display further information. The default configuration is that
image.png
if you want to display the proportion, you need to rewrite the formater method yourself, as shown in the figure below

 tooltip: {
  trigger: 'item',
  formatter: function (params) {
    // 只返回第一列数据
    return params.data[0] + '(' + params.percent + '%)'
  }
}

The effect is as follows:
image.png
the display effect is indeed not as beautiful as the official default, but it can be further controlled. Here is just a way to customize it.

These contents are not mentioned in the official website. I explored it myself and printed out the params information with console.log. I found that with the percent attribute, I don’t need to do the calculation myself.

Weekly Active Users: Histogram

<template>
  <v-chart :option="option" theme="auto" :autoresize="true" style="width: 100%; height: 300px" />
</template>

<script>
export default {
  data() {
    return {
      option: {
        dataset: {
          source: [
            ['count', 'week'],
            [13253, '周一'],
            [34235, '周二'],
            [26321, '周三'],
            [12340, '周四'],
            [24643, '周五'],
            [1322, '周六'],
            [1324, '周日']
          ]
        },
        xAxis: { type: 'category' },
        yAxis: {},
        series: [
          {
            type: 'bar',
            encode: {
              x: 'week',
              y: 'count'
            }
          }
        ]
      }
    }
  },
  methods: {}
}
</script>

<style></style>

Note that the following attributes must have
xAxis: { type: 'category' },
yAxis: {},
otherwise an inexplicable error will be reported uncaught (in promise) Error: xAxis “0” not found

Monthly Sales Volume: Line Chart

The following is actually a double line chart

<template>
  <v-chart :option="option" theme="auto" :autoresize="true" style="width: 100%; height: 300px" />
</template>

<script>
export default {
  data() {
    return {
      option: {
        dataset: {
          source: [
            ['estimate', 'actual', 'month'],
            [100, 120, '一月'],
            [120, 82, '二月'],
            [161, 91, '三月'],
            [134, 154, '四月'],
            [105, 162, '五月'],
            [160, 140, '六月'],
            [165, 145, '七月'],
            [114, 250, '八月'],
            [163, 134, '九月'],
            [185, 56, '十月'],
            [118, 99, '十一月'],
            [123, 123, '十二月']
          ]
        },
        xAxis: {
          type: 'category'
        },
        yAxis: {
          axisTick: {
            show: false
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          padding: [5, 10]
        },
        legend: {
          data: ['预计', '实际'],
          top: 20
        },
        series: [
          {
            type: 'line',
            name: '预计',
            smooth: true,
            encode: {
              x: 'month',
              y: 'estimate'
            },
            animationDuration: 2800,
            animationEasing: 'cubicInOut'
          },
          {
            type: 'line',
            name: '实际',
            smooth: true,
            encode: {
              x: 'month',
              y: 'actual'
            },
            animationDuration: 2800,
            animationEasing: 'quadraticOut'
          }
        ]
      }
    }
  },
  methods: {}
}
</script>

<style></style>

Summarize

It can be seen from the specific use above that it is more convenient to directly use the official packaged vue-echarts components. The configuration option is complex and changeable, and the secondary packaging is of little significance. It is also easy to use other types of charts on this basis.

The concept and configuration options of echarts will inevitably take some time to understand and become familiar with. Generally speaking, the learning cost is good, pay attention to the use of data set mode.

Development platform information

Platform name: One Two Three Development Platform
Introduction: Enterprise-level general development platform
Design information: csdn column
Open source address: Gitee
open source protocol: MIT
open source is not easy, welcome to favorite, like, comment.

Guess you like

Origin blog.csdn.net/seawaving/article/details/131434873