Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to encapsulate echarts in vue Project

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

In this article, the editor introduces in detail "how to encapsulate echarts in the vue project", the content is detailed, the steps are clear, and the details are handled properly. I hope that this article "how to encapsulate echarts in the vue project" can help you solve your doubts.

Scene

1. When using Echarts, you need to write a bunch of option. If you have to write one for each chart, there is a large amount of code in a file.

2. Inconvenient reuse

Demand

1. Easy to reuse

2. display the chart of the class, and the data is separated from the business and style, and only the data is transmitted.

3. There will be multiple charts to be used in the project. Automatic import with less code is achieved without the need for an import.

4. My chart is often used in large screen data visualization, using proportional scaling, so the chart can also be scaled automatically according to the interface zoom, and there is no need to call it manually.

5. The chart is configurable

Code overview

The files involved are as follows (see code for details):

| |-- src |-- components |-- chart |-- index.vue / / Chart single file component | Can be called by the interface |-- index.js / / automatically import the chart option in options |-- options / / the option where various charts are stored |-- bar / / any example |-- index.js |-- views |-- chartTest / / where the instance is located | |-- index.vue |-- index.scss |-- index.js |-- main.js / / globally introduce echarts chart to implement components--chart--index.vue |

A component called ChartView is defined here, which opens up four configurable properties: width width, height height, whether to automatically resize autoResize (default), and chart configuration chartOption.

Canvas is used by default to render the chart here, or you can use SVG. Choose it.

The specific code is as follows

/ / introduce the echarts core module, which provides the necessary interfaces for the use of echarts. Import * as echarts from 'echarts/core'// introduces bar chart, chart suffix is Chartimport {BarChart} from' echarts/charts'// to introduce prompt box, title, Cartesian coordinate system component, component suffix is Componentimport {TitleComponent, TooltipComponent, GridComponent} from 'echarts/components'// to introduce Canvas renderer Note that the introduction of CanvasRenderer or SVGRenderer is a necessary step for import {CanvasRenderer} from 'echarts/renderers'// to register the required components echarts.use ([TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer]) export default {name:' ChartView', props: {type: String, default: '100%'}, height: {type: String, default: '350px'} AutoResize: {type: Boolean, default: true}, chartOption: {type: Object, required: true}, type: {type: String, default: 'canvas'}}, data () {return {chart: null}}, watch: {chartOption: {deep: true Handler (newVal) {this.setOptions (newVal)}}, mounted () {this.initChart () if (this.autoResize) {window.addEventListener ('resize', this.resizeHandler)}}, beforeDestroy () {if (! this.chart) {return} if (this.autoResize) {window.removeEventListener (' resize') This.resizeHandler)} this.chart.dispose () this.chart = null}, methods: {resizeHandler () {this.chart.resize ()}, initChart () {this.chart = echarts.init (this.$refs.chart,'', {renderer: this.type}) this.chart.setOption (this.chartOption) this.chart.on ('click', this.handleClick)} HandleClick (params) {this.$emit ('click', params)}, setOptions (option) {this.clearChart () this.resizeHandler () if (this.chart) {this.chart.setOption (option)}}, refresh () {this.setOptions (this.chartOption)} ClearChart () {this.chart & & this.chart.clear ()}} components--chart--index.js

Here, we mainly use require.context to import the chart traversal defined in options, so that there is no need to import one by one in the code, especially when there are many charts.

Const modulesFiles = require.context ('. / options', true, / index.js$/) let modules = {} modulesFiles.keys () .forEach (item = > {modules = Object.assign ({}, modules, modulesFiles (item) .default)}) export default modulescomponents--chart--options

Here's how to encapsulate the chart you want.

Choose a random example on the official example of Echarts

Create a new bar directory under options and a new index.js file under the bar directory. It's just a personal habit. I like to store each chart in a separate folder. If you don't like this way, you can directly js files without putting directories, but the components--chart--index.js should be modified accordingly)

Copy the option code of the example directly

The specific code of index.js is as follows

Const testBar = (data) = > {const defaultConfig = {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'}]} const opt = Object.assign ({}, defaultConfig) return opt} export default {testBar}

TestBar method can pass parameters, specific use, the chart needs to configure properties, such as: data data, chart color. And so on can be passed as parameters.

Main.js

Here, the encapsulated Echarts component is introduced globally to facilitate the interface call. (as for the way of a single reference, there is no need to say much.)

The specific code is as follows:

Import eChartFn from'@ / components/chart/index.js'import ChartPanel from'@ / components/chart/index.vue'Vue.component (ChartPanel.name, ChartPanel) Vue.prototype.$eChartFn = eChartFnchartTest

Here is how to call the encapsulated bar diagram. The main code is as follows

Index.vueindex.jsexport default {name: 'chartTestView', data () {return {chartOpt: {}}, mounted () {}, created () {this.chartOpt = this.$eChartFn.testBar ()}, methods: {}, watch: {}}

The effect is as follows

You can try to drag the size of the browser, and you can see that the chart is also automatically scaled as the browser drags.

Code

Just go to the code in the directory of the code overview and look for it.

Summary

The various diagrams used by Echarts can basically be found on Echarts's official examples and Echarts visualization works sharing (out of service).

Above, encapsulated the chart component, according to the above, put the option configuration and related processing of the chart under the options folder, and transfer the corresponding option when calling the chart, which is only a few lines of code, which is more convenient.

Chart components are easy to reuse and can be used directly.

Supplement

Comments said that want to dynamically modify the properties inside the option, slightly do an example, dynamically modify the data and color properties of the pie chart, this is a direct production can use the example, directly refer to the code on the line, not in detail. If you want to modify any attribute, just pass the parameter directly. You can pass specific parameters, or you can encapsulate the parameters into a json if you want to modify more attributes. Just know how to use it flexibly in packaged option.

The following is the new reference code

| |-- src |-- components |-- chart |-- options / / option where various charts are stored |-- pie / / pie example |-- index.js |-- views |-- chartTest / / instance location |-- index.vue |-- index.scss |-- index.js |

The code is called directly on one line.

This.chartOpt2 = this.$eChartFn.getPieChart ([100,23,43,65], ['# 36CBCBB,'# FAD337','# F2637Bobby,'# 975FE4'])

The effect is as follows:

Supplement 2: chart highlight polling, dispatchAction use

Effect picture

Usage

Just add: play-highlight= "true" attribute

The main implementation code is in the playHighlightAction method of the following file, which is implemented by calling the highlighted sample dispatchAction (see the end of the article) in the referenced echarts pie chart. It's just a simple highlight poll, and the specific implementation depends on the document style.

| |-- src |-- components |-- chart |-- index.js / / automatically import charts in options option attachment: echarts pie chart call highlight example dispatchAction var myChart = echarts.init (document.getElementById ('main')); var app = {} | Option = {title: {text:' pie chart program call highlight example', left:'center'}, tooltip: {trigger:'item', formatter:' {a} {b}: {c} {d}%'} Legend: {the layout of the orient:'vertical', / / legend list is oriented.' Horizontal''vertical' left:'left', data: ['direct access', 'email marketing', 'affiliate advertising', 'video advertising', 'search engine']}, series: [{name:' access source', type:'pie' Radius:'55%', center: ['50% email 60%'], data: [{value:335,name:' direct access'}, {value:310,name:' email marketing'}, {value:234 Name:' Alliance ads'}, {value:135,name:' Video Advertising'}, {value:1548,name:' search engine'},], emphasis: {itemStyle: {shadowBlur:10 ShadowOffsetX:0, shadowColor:'rgba App.currentIndex =-1; setInterval (() = > {var dataLen = option.series [0] .data.length; / / unhighlight the previously highlighted graphic myChart.dispatchAction ({type:'downplay', seriesIndex:0, dataIndex:app.currentIndex}) App.currentIndex = (app.currentIndex + 1)% dataLen; / / highlight the current drawing myChart.dispatchAction ({type:'highlight', seriesIndex:0, dataIndex:app.currentIndex}) / / display tooltip myChart.dispatchAction ({type:'showTip', seriesIndex:0, dataIndex:app.currentIndex})}, 1000); option & & myChart.setOption (option)

After reading this, the article "how to encapsulate echarts in the vue project" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about the article, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report