初学echarts做的vue小demo,绘制的柱状图和饼状图
前言
一、Vue前端搭建获取ECharts
1.1安装:从npm中获取
npm install echarts --save
1.2进入ECharts官网挑选示例
在ECharts官网上找一个自己想要的示例(这里我选择的是基础南丁格尔玫瑰图),新建一个Pie.vue,引入示例代码,写入初始化函数mounted()中
Pie.vue完整代码如下:
<template>
<div id="myChart" :style="{width: '800px', height: '600px'}"></div>
</template>
<script>
import axios from 'axios'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'FruitBar',
mounted(){
let _this = this
axios.get('http://localhost:8181/fruit/barVO').then(function (response) {
// 基于准备好的dom,初始化echarts实例
let myChart = _this.$echarts.init(document.getElementById('myChart'))
// 绘制图表
myChart.setOption({
title: {
text: '水果销量统计',
left: 'center',
top: 20,
textStyle: {
color: '#555555'
}
},
tooltip: {},
xAxis: {
data: response.data.names
},
yAxis: {},
series: [{
name: '销量',
type: 'bar',
data: response.data.values
}]
});
})
}
}
</script>
1.3写路由
在index.js中写入路由
{ path: '/fruitBar', component: FruitBar }
二、搭建后端服务
2.1使用Spring Initializr 创建Springboot项目
2.2 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.liwe</groupId>
<artifactId>springboot-fruit_echarts</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-fruit_echarts</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.3yml配置文件
spring: datasource: url: jdbc:mysql://localhost:3306/basketball?serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath:com/southwind/mapper/xml/*.xml server: port: 8181
3、后端代码实现
3.1Game实体类
package com.liwe.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.apache.ibatis.annotations.Insert;
import java.io.Serializable;
@Data
@EqualsAndHashCode(callSuper = false)
public class Game implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String name;
private Integer sale;
private String icon;
}
3.2配置跨域设置
package com.liwe.configuration;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrosConfiguration implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
.allowCredentials(true)
.maxAge(3600)
.allowedHeaders("*");
}
}
3.3mapper层
package com.liwe.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.liwe.entity.Game;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface GameMapper extends BaseMapper<Game> {
}
3.4DataUtil工具类
package com.liwe.util;
import java.util.HashMap;
import java.util.Map;
public class DataUtil {
public static Map<String,String> createItemStyle(Integer sale){
String color = "";
if(sale<60){
color = "#96dee8";
}
if(sale>60 && sale<160){
color = "#c4ebad";
}
if(sale>160 && sale<300){
color = "#6be6c1";
}
if(sale>300 && sale<500){
color = "#3fb1e3";
}
if(sale>500){
color = "#a0a7e6";
}
Map<String,String> map = new HashMap<>();
map.put("color", color);
return map;
}
}
3.5vo层次(BarVo、PieVo、DataVo)
package com.liwe.vo;
import lombok.Data;
import java.util.List;
@Data
public class BarVO {
private List<String> names;
private List<DataVO> values;
}
package com.liwe.vo;
import lombok.Data;
import java.util.Map;
@Data
public class PieVO {
private Integer value;
private Map<String,String> itemStyle;
private String name;
}
package com.liwe.vo;
import lombok.Data;
import java.util.Map;
@Data
public class DataVO {
private Integer value;
private Map<String,String> itemStyle;
}
3.6service层
package com.liwe.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.liwe.entity.Game;
import com.liwe.vo.BarVO;
import com.liwe.vo.PieVO;
import java.util.List;
public interface GameService extends IService<Game> {
public BarVO barVOList();
public List<PieVO> pieVOList();
}
3.7impl层
package com.liwe.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liwe.entity.Game;
import com.liwe.mapper.GameMapper;
import com.liwe.service.GameService;
import com.liwe.util.DataUtil;
import com.liwe.vo.BarVO;
import com.liwe.vo.DataVO;
import com.liwe.vo.PieVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class GameServiceImpl extends ServiceImpl<GameMapper, Game> implements GameService {
@Autowired
private GameMapper gameMapper;
@Override
public BarVO barVOList() {
BarVO barVO=new BarVO();
//存放每个游戏的名称
List<String>names=new ArrayList<>();
//存放玩这个游戏的数量和对应的颜色(按数量进行判断)
List<DataVO> values=new ArrayList<>();
//先查出数据
List<Game> games=this.gameMapper.selectList(null);
for (Game game : games){
//将查出来的所有游戏名称进行循环唇乳
names.add(game.getName());
//创建一个DataVo对象
DataVO dataVO=new DataVO();
//将数量存入
dataVO.setValue(game.getSale());
//将玩这个游戏数量的人放入DataUtil里面判断返回对应的颜色进行存入
dataVO.setItemStyle(DataUtil.createItemStyle(game.getSale()));
values.add(dataVO);
}
barVO.setNames(names);
barVO.setValues(values);
//转换VO
return barVO;
}
@Override
public List<PieVO> pieVOList() {
List<PieVO> pieVOList=new ArrayList<>();
List<Game>games=this.gameMapper.selectList(null);
for (Game game:games){
PieVO pieVO=new PieVO();
pieVO.setValue(game.getSale());
pieVO.setName(game.getName());
pieVO.setItemStyle(DataUtil.createItemStyle(game.getSale()));
pieVOList.add(pieVO);
}
return pieVOList;
}
}
3.8控制层controller
package com.liwe.controller;
import com.liwe.entity.Game;
import com.liwe.service.GameService;
import com.liwe.vo.BarVO;
import com.liwe.vo.PieVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("game")
public class GameController {
@Autowired
private GameService gameService;
@GetMapping("/list")
public List<Game> list(){
return this.gameService.list();
}
@DeleteMapping("/delete/{id}")
public boolean delete(@PathVariable("id") Integer id){
return this.gameService.removeById(id);
}
@GetMapping("/find/{id}")
public Game find(@PathVariable("id") Integer id){
return this.gameService.getById(id);
}
@PutMapping("/update")
public boolean update(@RequestBody Game game){
return this.gameService.updateById(game);
}
@PostMapping("/add")
public boolean add(@RequestBody Game game){
return this.gameService.save(game);
}
@GetMapping("/barVO")
public BarVO barVO(){
return this.gameService.barVOList();
}
@GetMapping("/pieVO")
public List<PieVO> pieVO(){
return this.gameService.pieVOList();
}
}
4、前端代码实现
<template>
<div id="myChart" :style="{width: '800px', height: '600px'}"></div>
</template>
<script>
import axios from 'axios'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'GameBar',
mounted(){
let _this = this
axios.get('http://localhost:8181/game/barVO').then(function (response) {
// 基于准备好的dom,初始化echarts实例
let myChart = _this.$echarts.init(document.getElementById('myChart'))
// 绘制图表
myChart.setOption({
title: {
text: '游戏热度统计',
left: 'center',
top: 20,
textStyle: {
color: '#555555'
}
},
tooltip: {},
xAxis: {
data: response.data.names
},
yAxis: {},
series: [{
name: '热度',
type: 'bar',
data: response.data.values
}]
});
})
}
}
</script>
<template>
<div id="myChart" :style="{width: '800px', height: '600px'}"></div>
</template>
<script>
import axios from 'axios'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'GamePie',
mounted(){
let _this = this
axios.get('http://localhost:8181/game/pieVO').then(function (response) {
// 基于准备好的dom,初始化echarts实例
let myChart = _this.$echarts.init(document.getElementById('myChart'))
// 绘制图表
myChart.setOption({
backgroundColor: '#2c343c',
title: {
text: '游戏热度统计',
left: 'center',
top: 20,
textStyle: {
color: '#ccc'
}
},
tooltip: {
trigger: 'item'
},
visualMap: {
show: false,
min: 80,
max: 600,
inRange: {
colorLightness: [0, 1]
}
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '55%',
center: ['50%', '50%'],
data: response.data.sort(function (a, b) { return a.value - b.value; }),
roseType: 'radius',
label: {
color: 'rgba(255, 255, 255, 0.3)'
},
labelLine: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.3)'
},
smooth: 0.2,
length: 10,
length2: 20
},
itemStyle: {
color: '#c23531',
shadowBlur: 200,
shadowColor: 'rgba(0, 0, 0, 0.5)'
},
animationType: 'scale',
animationEasing: 'elasticOut',
// eslint-disable-next-line no-unused-vars
animationDelay: function (idx) {
return Math.random() * 200;
}
}
]
});
})
}
}
</script>
<template>
<div id="myChart" :style="{width: '800px', height: '600px'}"></div>
</template>
<script>
import axios from 'axios'
export default {
// eslint-disable-next-line vue/multi-word-component-names
name: 'GamePie',
mounted(){
let _this = this
axios.get('http://localhost:8181/game/pieVO').then(function (response) {
// 基于准备好的dom,初始化echarts实例
let myChart = _this.$echarts.init(document.getElementById('myChart'))
// 绘制图表
myChart.setOption({
backgroundColor: '#2c343c',
title: {
text: '游戏热度统计',
left: 'center',
top: 20,
textStyle: {
color: '#ccc'
}
},
tooltip: {
trigger: 'item'
},
visualMap: {
show: false,
min: 80,
max: 600,
inRange: {
colorLightness: [0, 1]
}
},
series: [
{
name: '访问来源',
type: 'pie',
radius: '55%',
center: ['50%', '50%'],
data: response.data.sort(function (a, b) { return a.value - b.value; }),
roseType: 'radius',
label: {
color: 'rgba(255, 255, 255, 0.3)'
},
labelLine: {
lineStyle: {
color: 'rgba(255, 255, 255, 0.3)'
},
smooth: 0.2,
length: 10,
length2: 20
},
itemStyle: {
color: '#c23531',
shadowBlur: 200,
shadowColor: 'rgba(0, 0, 0, 0.5)'
},
animationType: 'scale',
animationEasing: 'elasticOut',
// eslint-disable-next-line no-unused-vars
animationDelay: function (idx) {
return Math.random() * 200;
}
}
]
});
})
}
}
</script>
5、效果实现