search
HomeWeb Front-endJS TutorialDetailed tutorial on using Vue to develop dynamic refresh Echarts components

This article mainly introduces the detailed tutorial of using Vue to develop dynamically refreshing Echarts components. Friends who need it can refer to the following

Requirement background: Dashboard is the "face" of the current enterprise's back-end products, how to be more real-time Efficient and cool display of statistical data is a question worthy of consideration by front-end development engineers and UI designers. Today, we will start from scratch, encapsulating an Echarts line chart component that dynamically renders data, and start thinking about more interesting components together.

Preparation work

Project structure construction

Due to production needs (actually laziness), Therefore, this tutorial uses ==vue-cli== to build the infrastructure of the project.

npm install -g vue-cli
vue init webpack vue-charts
cd vue-charts
npm run dev


Install Echarts

Use npm to install directly.

npm install Echarts --save


Introducing Echarts

//在main.js加入下面两行代码
import echarts from 'echarts'
Vue.prototype.$echarts = echarts //将echarts注册成Vue的全局属性

At this point, the preparation work has been completed.

Static Component Development

Because I was deeply poisoned by the article "React Programming Thoughts", the author is also accustomed to gradually iterating from basic to advanced when developing components.

The purpose of the static component is very simple, which is to render the Echarts chart onto the page.

Create a new Chart.vue file

<template>
 <p :id="id" :style="style"></p>
</template>
<script>
export default {
 name: "Chart",
 data() {
  return {
   //echarts实例
   chart: ""  
  };
 },
 props: {
  //父组件需要传递的参数:id,width,height,option
  id: {
   type: String
  },
  width: {
   type: String,
   default: "100%"
  },
  height: {
   type: String,
   default: "300px"
  },
  option: {
   type: Object,
   //Object类型的prop值一定要用函数return出来,不然会报错。原理和data是一样的,
   //使用闭包保证一个vue实例拥有自己的一份props
   default() {
    return {
     title: {
      text: "vue-Echarts"
     },
     legend: {
      data: ["销量"]
     },
     xAxis: {
      data: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子","tuoxie"]
     },
     series: [
      {
       name: "销量",
       type: "line",
       data: [5, 20, 36, 10, 10, 70]
      }
     ]
    };
   }
  }
 },
 computed: {
  style() {
   return {
    height: this.height,
    width: this.width
   };
  }
 },
 mounted() {
  this.init();
 },
 methods: {
  init() {
   this.chart = this.$echarts.init(document.getElementById(this.id));
   this.chart.setOption(this.option);
  }
 }
};
</script>

The above file realizes rendering a simple line chart to the page Components, how about they are very simple? The simplest method to use is as follows:

App.vue

<template>
 <p id="app">
  <Chart id="test"/>
 </p>
</template>
<script>
import Chart from "./components/Chart";
export default {
 name: "App",
 data() {},
 components: {
  Chart
 }
}
</script>

At this point, when you run the program you should see the following Effect:

First iteration

Now that we have a basic version, let’s take a look at what to do It's still not satisfactory:

  1. The chart cannot be automatically scaled according to the window size. Although the width is set to 100%, the chart will not be re-rendered until the page is refreshed, which will cause The user experience becomes poor.

  2. Charts are currently unable to automatically refresh data

Let’s implement these two points:

Auto scaling

Echarts itself does not support automatic scaling, but Echarts provides us with the resize method.

//在init方法中加入下面这行代码
window.addEventListener("resize", this.chart.resize);

With just this sentence, we have realized the need for the chart to adapt to the window size.

Support automatic data refresh

Because Echarts is data-driven, which means that as long as we reset the data, the chart will follow Re-rendering is the basis for realizing this requirement. Let's imagine again that if you want to support automatic refresh of data, you must have a listener that can monitor data changes in real time and then tell Echarts to reset the data. Fortunately, Vue provides us with the ==watcher== function, through which we can easily implement the above functions:

//在Chart.vue中加入watch
 watch: {
  //观察option的变化
  option: {
   handler(newVal, oldVal) {
    if (this.chart) {
     if (newVal) {
      this.chart.setOption(newVal);
     } else {
      this.chart.setOption(oldVal);
     }
    } else {
      this.init();
    }
   },
   deep: true //对象内部属性的监听,关键。
  }
 }


The above code implements our monitoring of property changes in the option object. Once the data in the option changes, the chart will be re-rendered.

Achieve dynamic refresh

The next step, I think everyone knows, is to regularly pull data from the background, and then update the option of the parent component Just fine. There are two questions that need to be considered here:

  1. If the chart requires adding one data per second, how should the data request be performed to achieve a balance between performance and user experience?

  2. Should the code for dynamically updating data be placed in the parent component or the child component?

Regarding the first question, obtaining the server data in real time every second is definitely the most accurate. There are two solutions:

  • Request to the background once per second

  • Maintain a long connection, and the background pushes data to the front end once per second

One solution undoubtedly causes a great waste of performance and resources; unless the real-time requirements are particularly high (stock system), this method is not recommended;

The second solution requires the use of web Socket, but in Additional development work is required on the server side.

Based on the actual needs of the project (the real-time requirements are not high, and the data generated in the background also has a certain delay), the author adopted the following solution:

  1. The front-end every other Data is requested from the background once a minute, and it is the data of the previous minute of the current time;

  2. The front end will set the above data to the chart every second.

关于第二个问题:笔者更倾向于将Chart组件设计成纯组件,即只接收父组件传递的数据进行变化,不在内部进行复杂操作;这也符合目前前端MVVM框架的最佳实践;而且若将数据传递到Chart组件内部再进行处理,一是遇到不需要动态渲染的需求还需要对组件进行额外处理,二是要在Chart内部做ajax操作,这样就导致Chart完全没有了可复用性。

接下来我们修改App.vue

<template>
 <p id="app">
  <Chart id="test" :option="option"/>
 </p>
</template>

<script>
import vueEcharts from "./components/vueEcharts";
export default {
 name: "App",
 data() {
  return {
   //笔者使用了mock数据代表从服务器获取的数据
   chartData: {
    xData: ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"],
    sData: [5, 20, 36, 10, 10, 70]
   }
  };
 },
 components: {
  Chart
 },
 mounted() {
  this.refreshData();
 },
 methods: {
  //添加refreshData方法进行自动设置数据
  refreshData() {
   //横轴数据
   let xData = this.chartData.xData,
    //系列值
     sData = this.chartData.sData;
   for (let i = 0; i < xData.length; i++) {
    //此处使用let是关键,也可以使用闭包。原理不再赘述
      setTimeout(() => {
     this.option.xAxis.data.push(xData[i]);
     this.option.series[0].data.push(sData[i]);
    }, 1000*i)//此处要理解为什么是1000*i
   }
  }
 }
};
</script>

至此我们就实现了图表动态数据加载,效果如下图:

 

总结

这篇教程通过一个动态图表的开发,传递了以下信息:

  • Echarts如何与Vue结合使用

  • Vue组件开发、纯组件与“脏”组件的区别

  • Vue watch的用法

  • let的特性

  • JavaScript EventLoop特性

  • ...

大家可以根据这个列表查漏补缺。

后续优化

  1. 这个组件还有需要需要优化的点,比如:

  2. 间隔时间应该可配置

  3. 每分钟从后台获取数据,那么图表展示的数据将会越来越多,越来越密集,浏览器负担越来越大,直到崩溃

  4. 没有设置暂停图表刷新的按钮

  5. ...

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Ajax+Struts2实现验证码验证功能(图文教程)

Ajax点击不断加载数据列表(图文教程)

非常实用的ajax用户注册模块

The above is the detailed content of Detailed tutorial on using Vue to develop dynamic refresh Echarts components. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.