PrefaceWhen we are working on a project, we often need some statistical charts to display our data. As a web developer, being able to implement statistical charts is a skill we must have. I will show you how to implement a dynamic pie chart. 1. Environment Configuration1.1 Install acharts//npm is the same cnpm install echarts --save 1.2 Global ReferencesConfiguration in main.js //Introduce echarts import echarts from 'echarts' //Register component Vue.prototype.$echarts = echarts After registering the components globally, let's get down to business. The first step is to draw a donut chart. First the result picture: 2. Front-end implementation of donut chart2.1 Add a rendering box to the vue page first<template> <div class="test2" style="width:600px;height:400px;"> <div id="myChart" style="width:100%;height:278px;float:left;"></div> </div> </template> 2.2 Front-end logic implementationIntroducing echart import * as echarts from 'echarts' Note: There is a big pit here. If you install a higher version of echarts, you must follow my instructions. Import echarts from 'echarts' Many people on the Internet share this, which will cause an error in initializing the init function. <script> import * as echarts from 'echarts' export default { name: 'test2', data () { return { queryInfo: { query: "", pageNum: 1, pageSize: 4, //The backend requests 4 data categories. If you have more than one, change this parameter}, queryInfof: { query: "", pageNum: 1, pageSize: 100, }, myChart: '', opinionData2: {"itemStyle":"#3F8FFF","name":"Threat Attack Log","value":200}, {"itemStyle":"#6DC8EC","name":"Audit URL exception","value":388}, {"itemStyle":"#1FC48D","name":"Normal network log","value":5287}, {"itemStyle":"red","name":"Traffic log abnormality","value":320} ] } }, mounted: function () { this.drawLine(); }, methods: { async drawLine() { // Call post request /* const { data: res } = await this.$http.get("alldate", { params: this.queryInfo }); if (res.flag != "success") { return this.$message.error("Failed to obtain the data!!!"); } console.log(res.flag) this.opinionData2 = res.opinionData2; // Assign the returned data*/ this.myChart = echarts.init(document.getElementById('myChart')) this.myChart.setOption({ title: text: 'Network Log Abnormal Traffic Analysis', // Main Title subtext: '', // Subtitle x: 'left' // x-axis alignment}, grid: { containLabel: true }, tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {d}%' }, // color: ['#1FC48D', '#F5A60A', '#6DC8EC', '#3F8FFF'], color: ['#1FC48D', 'red', '#6DC8EC', '#3F8FFF'], // backgroundColor: '#ffffff', legend: { orient: 'vertical', icon: 'circle', align: 'left', x: 'right', y: 'bottom', data: ['Audit URL abnormality', 'Normal network log', 'Traffic log abnormality', 'Threat attack log'] }, series: [ { name: 'Network Log Status', type: 'pie', radius: ['50%', '70%'], avoidLabelOverlap: false, center: ['40%', '50%'], itemStyle: { emphasis: shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }, color: function (params) { // Custom colors var colorList = ['#1FC48D', 'red', '#6DC8EC', '#3F8FFF'] return colorList[params.dataIndex] } }, data: this.opinionData2 } ] }) }, } } </script> 2.3 Display (you can change the front-end style according to your needs)3. Implementation of front-end and back-end data interaction3.1 Create a database Table structure: (Create according to your business needs) Table Data 3.2 Writing background code3.2.1 Create QueryInfo class under bean package This class implements getting the number of data requested by the front end. Equivalent to paging functionality. public class QueryInfo { private String query; private int pageNum=1; private int pageSize=1; public QueryInfo() { } public QueryInfo(String query, int pageNum, int pageSize) { this.query = query; this.pageNum = pageNum; this.pageSize = pageSize; } public String getQuery() { return query; } public int getPageNum() { return pageNum; } public int getPageSize() { return pageSize; } public void setQuery(String query) { this.query = query; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } @Override public String toString() { return "QueryInfo{" + "query='" + query + '\'' + ", pageNum=" + pageNum + ", pageSize=" + pageSize + '}'; } } 3.2.2 Create Showdate class under bean package public class Showdate { private String name; private String itemStyle; private int value; public Showdate() { } public Showdate(String name, String itemStyle, int value) { this.name = name; this.itemStyle = itemStyle; this.value = value; } public String getName() { return name; } public void setName1(String name) { this.name= name; } public String getItemStyle() { return itemStyle; } public void setItemStyle(String itemStyle) { this.itemStyle = itemStyle; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } @Override public String toString() { return "Showdate{" + "name='" + name + '\'' + ", itemStyle='" + itemStyle + '\'' + ", value=" + value + '}'; } } 3.2.3 Create Mapper under resources 1. Create ShowDataMapper.xml in Mapper <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.naughty.userlogin02.dao.ShowdateDao"> <select id="getAlldate" resultType="com.naughty.userlogin02.bean.Showdate"> SELECT * FROM date1 <if test="name!=null"> WHERE name like #{name} </if> LIMIT #{pageStart},#{pageSize} </select> <update id="updatenew"> UPDATE date1 SET value = #{count} WHERE name = #{name} </update> </mapper> 2. Create application.yml under resources to configure the database and port number #mysql spring: datasource: #MySQL configuration driverClassName: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/weblog?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC Username: root password: root mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.demo.model server: port: 9000 3.2.4 Create ShowdateDao under Dao There are two interfaces in it. If you need to operate the database, you need to write interface methods in ShowdateDao; import com.naughty.userlogin02.bean.Showdate; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface ShowdateDao { public List<Showdate> getAlldate(@Param("name") String name, @Param("pageStart") int pageStart, @Param("pageSize") int pageSize); public int updatenew(String name, int count); } 3.2.5 Create ShowdateController under Controller In ShowdateController, you need to annotate the use of space @Autowired ShowdateDao showdateDao; //You need to pass to the front-end database table @Autowired FlowDao flowDao; //The effect database table of your data source package com.naughty.userlogin02.controller; import com.alibaba.fastjson.JSON; import com.naughty.userlogin02.bean.*; import com.naughty.userlogin02.dao.CheckDao; import com.naughty.userlogin02.dao.FlowDao; import com.naughty.userlogin02.dao.SafeDao; import com.naughty.userlogin02.dao.ShowdateDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.List; import java.util.Stack; @RestController public class ShowdateController { @Autowired ShowdateDao showdateDao; @Autowired FlowDao flowDao; //Refresh log data at the front desk @CrossOrigin @RequestMapping("/alldate")//Front-end request channel public String getAlldateList(QueryInfo queryInfo){ System.out.println(queryInfo); int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize(); List<Showdate> dates = showdateDao.getAlldate("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize()); for(int i =0;i<dates.size();i++){ System.out.println(dates.get(i).toString()); } //Verification//Encapsulate the verified traffic log HashMap<String, Object> res = new HashMap<>(); res.put("flag","success"); res.put("opinionData2",dates); String date_json = JSON.toJSONString(res); System.out.println(date_json.toString()); return date_json; } //The implementation method of the database data source is to change the data in the database table Date1 @RequestMapping("/getupdata") public String updateDate(QueryInfo queryInfo){ String s = "Traffic log exception"; String s1 = "Audit URL exception"; String s2 = "Threat attack log"; String s3 = "Normal network log"; /*int count = getUserList(queryInfo); int count1 =getChickList(queryInfo); //The four methods need to be implemented by you according to the specific business int count2 =getSafeDate(queryInfo); int count3 =allBlognum(queryInfo)-(count+count1+count2);*/ showdateDao.updatenew(s,count); showdateDao.updatenew(s1,count1); showdateDao.updatenew(s2,count2); int i = showdateDao.updatenew(s3,count3); System.out.println("Exception type: "+s); System.out.println("Number of abnormal logs:"+count); String str = i >0?"success":"error"; return str; } } 3.2.6 Modify the front-end interface Js full code: <script> import * as echarts from 'echarts' export default { name: 'test2', data () { return { queryInfo: { query: "", pageNum: 1, pageSize: 4, }, queryInfof: { query: "", pageNum: 1, pageSize: 100, }, myChart: '', opinionData2: // Clear front-end test data] } }, mounted: function () { this.drawLine(); }, created() { this.getdateList(); //Refresh database data every time you enter the page to achieve dynamic data binding}, methods: { async drawLine() { // Call post request to get the value of the backend database const { data: res } = await this.$http.get("alldate", { params: this.queryInfo }); if (res.flag != "success") { return this.$message.error("Failed to obtain the data!!!"); } console.log(res.flag) this.opinionData2 = res.opinionData2; // Assign the returned data this.myChart = echarts.init(document.getElementById('myChart')) this.myChart.setOption({ title: text: 'Network Log Abnormal Traffic Analysis', // Main Title subtext: '', // Subtitle x: 'left' // x-axis alignment}, grid: { containLabel: true }, tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {d}%' }, // color: ['#1FC48D', '#F5A60A', '#6DC8EC', '#3F8FFF'], color: ['#1FC48D', 'red', '#6DC8EC', '#3F8FFF'], // backgroundColor: '#ffffff', legend: { orient: 'vertical', icon: 'circle', align: 'left', x: 'right', y: 'bottom', data: ['Audit URL abnormality', 'Normal network log', 'Traffic log abnormality', 'Threat attack log'] }, series: [ { name: 'Network Log Status', type: 'pie', radius: ['50%', '70%'], avoidLabelOverlap: false, center: ['40%', '50%'], itemStyle: { emphasis: shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' }, color: function (params) { // Custom colors var colorList = ['#1FC48D', 'red', '#6DC8EC', '#3F8FFF'] return colorList[params.dataIndex] } }, data: this.opinionData2 } ] }) }, async getdateList() { // Call post request const { data: res } = await this.$http.get("getupdata", { params: this.queryInfof }); if (res != "success") { return this.$message.error("Failed to obtain the data!!!"); } console.log(res) }, } } </script> Backend return data: This is the end of this article about Springboot using vue+echarts front-end and back-end interaction to implement dynamic pie charts. For more related Springboot vue dynamic pie chart content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: Detailed explanation of SRIOV pass-through configuration and performance testing based on KVM
>>: MySQL 5.6 root password modification tutorial
To create a flex container, simply add a display:...
The biggest bottleneck of using zabbix is the d...
need: Implement dynamic display of option values ...
This article is from the Apache Spark Meetup held...
When a web project gets bigger and bigger, its CS...
1. Background Sysbench is a stress testing tool t...
There are many tags in XHTML, but only a few are ...
Table of contents Preface Demand Analysis Mysql u...
We can view the installation path of mysql throug...
Here's a solution to the problem where margin...
Preface As we all know, the nginx configuration f...
Copy code The code is as follows: <HTML> &l...
Use "onInput(event)" to detect whether ...
I logged into the backend to check the solution t...
Preface “When it comes to image processing, we of...