How does the Vue project elegantly encapsulate echarts? Method introduction
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!
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
):
|-- 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图表
Implementationcomponents--chart--index.vue
Here defines a file named
ChartViewThe 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
, choose your own The specific code is as follows
<pre class='brush:php;toolbar:false;'><template>
<div class="chart">
<div ref="chart" :style="{ height: height, width: width }" />
</div>
</template>
<script>
// 引入 echarts 核心模块,核心模块提供了 echarts 使用必须要的接口。
import * as echarts from &#39;echarts/core&#39;
// 引入柱状图图表,图表后缀都为 Chart
import {
BarChart
} from &#39;echarts/charts&#39;
// 引入提示框,标题,直角坐标系组件,组件后缀都为 Component
import {
TitleComponent,
TooltipComponent,
GridComponent
} from &#39;echarts/components&#39;
// 引入 Canvas 渲染器,注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import {
CanvasRenderer
} from &#39;echarts/renderers&#39;
// 注册必须的组件
echarts.use(
[TitleComponent, TooltipComponent, GridComponent, BarChart, CanvasRenderer]
)
export default {
name: &#39;ChartView&#39;,
props: {
width: {
type: String,
default: &#39;100%&#39;
},
height: {
type: String,
default: &#39;350px&#39;
},
autoResize: {
type: Boolean,
default: true
},
chartOption: {
type: Object,
required: true
},
type: {
type: String,
default: &#39;canvas&#39;
}
},
data() {
return {
chart: null
}
},
watch: {
chartOption: {
deep: true,
handler(newVal) {
this.setOptions(newVal)
}
}
},
mounted() {
this.initChart()
if (this.autoResize) {
window.addEventListener(&#39;resize&#39;, this.resizeHandler)
}
},
beforeDestroy() {
if (!this.chart) {
return
}
if (this.autoResize) {
window.removeEventListener(&#39;resize&#39;, this.resizeHandler)
}
this.chart.dispose()
this.chart = null
},
methods: {
resizeHandler() {
this.chart.resize()
},
initChart() {
this.chart = echarts.init(this.$refs.chart, &#39;&#39;, {
renderer: this.type
})
this.chart.setOption(this.chartOption)
this.chart.on(&#39;click&#39;, this.handleClick)
},
handleClick(params) {
this.$emit(&#39;click&#39;, 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()
}
}
}
</script></pre>
components--chart--index.js
Here we mainly use
require.contextto 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. <pre class='brush:php;toolbar:false;'>const modulesFiles = require.context(&#39;./options&#39;, true, /index.js$/)
let modules = {}
modulesFiles.keys().forEach(item => {
modules = Object.assign({}, modules, modulesFiles(item).default)
})
export default modules</pre>
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 options
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.js
The specific code 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
The 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 '@/components/chart/index.js' import ChartPanel from '@/components/chart/index.vue' Vue.component(ChartPanel.name, ChartPanel) Vue.prototype.$eChartFn = eChartFn
chartTest
Here is how to call the encapsulated
barChart, the main code is as follows
index.vue<pre class='brush:php;toolbar:false;'><chart-view class="chart-content" :chart-option="chartOpt" :auto-resize="true" height="100%" /></pre>
index.js
export default { name: 'chartTestView', data() { return { chartOpt: {} } }, mounted() {}, created() { this.chartOpt = this.$eChartFn.testBar() }, methods: { }, watch: {} }
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.Code
Just click the directory of
Code Overviewand go to
Code to look for it. https://github.com/liyoro/vue-skill
Summary
Echarts uses various Charts can basically be found on
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
图表的data
和color
属性,这个是直接生产就可以使用的例子了,直接参考代码就行了,不详细说了。想修改什么属性,直接传参就行。传具体参数可以,想修改的属性多了就把参数封装成一个json
传也可以。懂得在封装的option
里面灵活使用就行。
以下是新增的参考代码
|-- src |-- components |-- chart |-- options // 存放各种图表的option |-- pie // pie例子 |-- index.js |-- views |-- chartTest // 实例所在 |-- index.vue |-- index.scss |-- index.js
代码使用都是直接一行调用的
this.chartOpt2 = this.$eChartFn.getPieChart([100, 23, 43, 65], ['#36CBCB', '#FAD337', '#F2637B', '#975FE4'])
效果如下:
补充2:图表高亮轮询,dispatchAction使用
效果图
使用方法
加上:play-highlight="true"
属性就行
<chart-view class="chart-content" :chart-option="chartOpt2" :auto-resize="true" :play-highlight="true" height="100%" />
主要实现的代码在如下文件的playHighlightAction
方法里面,参考的echarts 饼图调用高亮示例 dispatchAction实现的。只是简单的高亮轮询,具体各种实现就自己看文档调样式了。
|-- src |-- components |-- chart |-- index.js // 实现自动化导入options里的图表option
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!

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1
Powerful PHP integrated development environment

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools
