Table of Contents
Scenario
Requirements
):
Here defines a file named
The component has 4 configurable properties: width
to traverse and import the charts defined in
In
The specific code is as follows:
Chart, the main code is as follows
The effect is as follows
and go to
and
补充
补充2:图表高亮轮询,dispatchAction使用
使用方法
Home Web Front-end Vue.js How does the Vue project elegantly encapsulate echarts? Method introduction

How does the Vue project elegantly encapsulate echarts? Method introduction

Mar 10, 2022 pm 07:48 PM
vue project

vueHow does the project elegantly encapsulate echarts? The following article will introduce to you a more elegant way to encapsulate echarts in the Vue project. I hope it will be helpful to you!

How does the Vue project elegantly encapsulate echarts? Method introduction

Scenario

  • 1. When using Echarts, you need to write a bunch of option , if you have to write one for each chart, the amount of code in one file will be very large
  • 2. It is inconvenient to reuse

Requirements

  • 1. Convenient reuse
  • 2. For display charts, data is separated from business and style. Just transfer data.
  • 3. There will be multiple charts that need to be used in the project. To achieve automatic import with less code, you don’t need to import them one by one. 4. My charts are often used in large-screen data visualization, and the method is proportional scaling, so the charts are also It can automatically scale according to the interface scaling, no need to call it manually. [Related recommendations: vuejs video tutorial]
  • 5. Charts can be configured
  • Code Overview
  • The files involved are as follows (specific reference
Code

):

|-- src
    |-- components
        |-- chart
            |-- index.vue    // 图表单文件组件,供界面调用
            |-- index.js    // 实现自动化导入options里的图表option
            |-- options    // 存放各种图表的option
                |-- bar    // 随便一例子
                    |-- index.js
    |-- views
        |-- chartTest    // 实例所在
            |-- index.vue
            |-- index.scss
            |-- index.js
|-- main.js    // 全局引入echarts图表
Copy after login

Implementationcomponents--chart--index.vue

Here defines a file named

ChartView

The component has 4 configurable properties: width

width

, heightheight, whether to automatically adjust the sizeautoResize (default is), chart configurationchartOption. By default, Canvas is used to render the chart. You can also use

SVG

, choose your own The specific code is as follows<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;template&gt; &lt;div class=&quot;chart&quot;&gt; &lt;div ref=&quot;chart&quot; :style=&quot;{ height: height, width: width }&quot; /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; // 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。 import * as echarts from &amp;#39;echarts/core&amp;#39; // 引入柱状图图表,图表后缀都为 Chart import { BarChart } from &amp;#39;echarts/charts&amp;#39; // 引入提示框,标题,直角坐标系组件,组件后缀都为 Component import { TitleComponent, TooltipComponent, GridComponent } from &amp;#39;echarts/components&amp;#39; // 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步 import { CanvasRenderer } from &amp;#39;echarts/renderers&amp;#39; // 注册必须的组件 echarts.use( [TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer] ) export default { name: &amp;#39;ChartView&amp;#39;, props: { width: { type: String, default: &amp;#39;100%&amp;#39; }, height: { type: String, default: &amp;#39;350px&amp;#39; }, autoResize: { type: Boolean, default: true }, chartOption: { type: Object, required: true }, type: { type: String, default: &amp;#39;canvas&amp;#39; } }, data() { return { chart: null } }, watch: { chartOption: { deep: true, handler(newVal) { this.setOptions(newVal) } } }, mounted() { this.initChart() if (this.autoResize) { window.addEventListener(&amp;#39;resize&amp;#39;, this.resizeHandler) } }, beforeDestroy() { if (!this.chart) { return } if (this.autoResize) { window.removeEventListener(&amp;#39;resize&amp;#39;, this.resizeHandler) } this.chart.dispose() this.chart = null }, methods: { resizeHandler() { this.chart.resize() }, initChart() { this.chart = echarts.init(this.$refs.chart, &amp;#39;&amp;#39;, { renderer: this.type }) this.chart.setOption(this.chartOption) this.chart.on(&amp;#39;click&amp;#39;, this.handleClick) }, handleClick(params) { this.$emit(&amp;#39;click&amp;#39;, params) }, setOptions(option) { this.clearChart() this.resizeHandler() if (this.chart) { this.chart.setOption(option) } }, refresh() { this.setOptions(this.chartOption) }, clearChart() { this.chart &amp;&amp; this.chart.clear() } } } &lt;/script&gt;</pre><div class="contentsignin">Copy after login</div></div> components--chart--index.js

Here we mainly use

require.context

to traverse and import the charts defined in

options

, so there is no need to add them in the code import one by one, especially when there are many charts. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>const modulesFiles = require.context(&amp;#39;./options&amp;#39;, true, /index.js$/) let modules = {} modulesFiles.keys().forEach(item =&gt; { modules = Object.assign({}, modules, modulesFiles(item).default) }) export default modules</pre><div class="contentsignin">Copy after login</div></div>components--chart--optionsHere is how to encapsulate the chart you want

In

Echarts official example

(https:/ /echarts.apache.org/examples/zh/index.html)

Create a new

under How does the Vue project elegantly encapsulate echarts? Method introductionoptions

bar

directory, create a new index.js file in the bar directory. (It’s just a personal habit. I like each chart to be stored in a separate folder. If you don’t like this method, you can leave the directory and directly use the js file, but components--chart--index.js must be modified accordingly. Below) Directly copy the option code of the example

index.jsThe specific code is as follows

const testBar = (data) => {
  const defaultConfig = {
    xAxis: {
      type: &#39;category&#39;,
      data: [&#39;Mon&#39;, &#39;Tue&#39;, &#39;Wed&#39;, &#39;Thu&#39;, &#39;Fri&#39;, &#39;Sat&#39;, &#39;Sun&#39;]
    },
    yAxis: {
      type: &#39;value&#39;
    },
    series: [{
      data: [120, 200, 150, 80, 70, 110, 130],
      type: &#39;bar&#39;
    }]
  }

  const opt = Object.assign({}, defaultConfig)
  return opt
}

export default {
  testBar
}
Copy after login

testBarThe method can pass parameters. When used specifically, the attributes that need to be configured for the chart, such as data data, chart color, etc., can be passed as parameters.

main.jsHere, the encapsulated Echarts component is introduced globally to facilitate interface calls. (As for the method of single reference, there is no need to say more)

The specific code is as follows:

import eChartFn from &#39;@/components/chart/index.js&#39;
import ChartPanel from &#39;@/components/chart/index.vue&#39;
Vue.component(ChartPanel.name, ChartPanel)
Vue.prototype.$eChartFn = eChartFn
Copy after login

chartTest

Here is how to call the encapsulated

bar

Chart, the main code is as follows

index.vue<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;chart-view class=&quot;chart-content&quot; :chart-option=&quot;chartOpt&quot; :auto-resize=&quot;true&quot; height=&quot;100%&quot; /&gt;</pre><div class="contentsignin">Copy after login</div></div>index.js

export default {
  name: &#39;chartTestView&#39;,
  data() {
    return {
      chartOpt: {}
    }
  },
  mounted() {},
  created() {
    this.chartOpt = this.$eChartFn.testBar()
  },
  methods: {
  },
  watch: {}
}
Copy after login

The effect is as follows

Yes Try dragging the size of the browser. You can see that the chart automatically scales as the browser is dragged.

How does the Vue project elegantly encapsulate echarts? Method introductionCode

Just click the directory of

Code Overview

and go to

Code

to look for it. https://github.com/liyoro/vue-skill

  • Summary

  • Echarts uses various Charts can basically be found on
Echarts official examples

and

Echarts visual work sharing

, especially Echarts visual work sharing. When doing projects, you can go refer to. The above encapsulates the chart component. According to the above method, put the

option

configuration and related processing of the chart under the options folder. Passing the corresponding option when calling the chart only requires a few lines of code, which is relatively convenient. chart The component is very easy to reuse and can be used directly.

补充

评论里说想动态修改option里面的属性,稍微做了个例子,动态修改pie图表的datacolor属性,这个是直接生产就可以使用的例子了,直接参考代码就行了,不详细说了。想修改什么属性,直接传参就行。传具体参数可以,想修改的属性多了就把参数封装成一个json传也可以。懂得在封装的option里面灵活使用就行。

以下是新增的参考代码

|-- src
    |-- components
        |-- chart
            |-- options    // 存放各种图表的option
                |-- pie    // pie例子
                    |-- index.js
    |-- views
        |-- chartTest    // 实例所在
            |-- index.vue
            |-- index.scss
            |-- index.js
Copy after login

代码使用都是直接一行调用的

this.chartOpt2 = this.$eChartFn.getPieChart([100, 23, 43, 65], [&#39;#36CBCB&#39;, &#39;#FAD337&#39;, &#39;#F2637B&#39;, &#39;#975FE4&#39;])
Copy after login

效果如下:

How does the Vue project elegantly encapsulate echarts? Method introduction

补充2:图表高亮轮询,dispatchAction使用

效果图

How does the Vue project elegantly encapsulate echarts? Method introduction

使用方法

加上:play-highlight="true"属性就行

<chart-view class="chart-content" :chart-option="chartOpt2" :auto-resize="true" :play-highlight="true"    style="max-width:90%" />
Copy after login

主要实现的代码在如下文件的playHighlightAction方法里面,参考的echarts 饼图调用高亮示例 dispatchAction实现的。只是简单的高亮轮询,具体各种实现就自己看文档调样式了。

|-- src
    |-- components
        |-- chart
            |-- index.js    // 实现自动化导入options里的图表option
Copy after login

(学习视频分享:vuejs教程web前端

The above is the detailed content of How does the Vue project elegantly encapsulate echarts? Method introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
How to use mobile gesture operations in Vue projects How to use mobile gesture operations in Vue projects Oct 08, 2023 pm 07:33 PM

How to use mobile gesture operations in Vue projects With the popularity of mobile devices, more and more applications need to provide a more friendly interactive experience on the mobile terminal. Gesture operation is one of the common interaction methods on mobile devices, which allows users to complete various operations by touching the screen, such as sliding, zooming, etc. In the Vue project, we can implement mobile gesture operations through third-party libraries. The following will introduce how to use gesture operations in the Vue project and provide specific code examples. First, we need to introduce a special

How to run vue project in webstorm How to run vue project in webstorm Apr 08, 2024 pm 01:57 PM

To run a Vue project using WebStorm, you can follow these steps: Install Vue CLI Create a Vue project Open WebStorm Start a development server Run the project View the project in the browser Debug the project in WebStorm

How to create a vue project in webstorm How to create a vue project in webstorm Apr 08, 2024 pm 12:03 PM

Create a Vue project in WebStorm by following these steps: Install WebStorm and the Vue CLI. Create a Vue project template in WebStorm. Create the project using Vue CLI commands. Import existing projects into WebStorm. Use the "npm run serve" command to run the Vue project.

TypeError: Cannot read property 'length' of undefined appears in Vue project, how to deal with it? TypeError: Cannot read property 'length' of undefined appears in Vue project, how to deal with it? Nov 25, 2023 pm 12:58 PM

In Vue project development, we often encounter error messages such as TypeError:Cannotreadproperty'length'ofundefined. This error means that the code is trying to read a property of an undefined variable, especially a property of an array or object. This error usually causes application interruption and crash, so we need to deal with it promptly. In this article, we will discuss how to deal with this error. Check variable definitions in code

How to export and import table data in Vue project How to export and import table data in Vue project Oct 08, 2023 am 09:42 AM

How to export and import table data in Vue projects requires specific code examples. Introduction In Vue projects, tables are one of the most common and important components. In actual projects, we often encounter the need to export table data to Excel or import data into Excel to display in a table. This article will introduce in detail how to export and import table data in the Vue project, and provide specific code examples. Table data export To implement table data export in Vue, we can use existing mature open source libraries

How does vscode package vue project_vscode package vue project method How does vscode package vue project_vscode package vue project method Apr 23, 2024 pm 03:43 PM

Step 1: Enter the Visual Studio Code interface, select File → Preferences → Settings Step 2: Open the settings.json file, enter: "npm.enableScriptExplorer": true, save Step 3: Restart Visual Studio Code, re-enter the interface, on the left The NPM script menu bar appears at the bottom of the side menu bar. Right-click build and run. Step 4: After execution, the packaging folder dist is successfully generated.

How to store and manage data locally in Vue projects How to store and manage data locally in Vue projects Oct 08, 2023 pm 12:05 PM

The local storage and management of data in the Vue project is very important. You can use the local storage API provided by the browser to achieve persistent storage of data. This article will introduce how to use localStorage in Vue projects for local storage and management of data, and provide specific code examples. Initializing data In the Vue project, you first need to initialize the data that needs to be stored locally. You can define the initial data in the data option of the Vue component and check whether it has been created through the created hook function

How to implement the photo upload function of high-photographers of different brands on the front end? How to implement the photo upload function of high-photographers of different brands on the front end? Apr 04, 2025 pm 05:42 PM

How to implement the photo upload function of different brands of high-photographers on the front end When developing front-end projects, you often encounter the need to integrate hardware equipment. for...

See all articles