最终效果展示:
echarst非常简单,就是使用的数据需要按照规定的格式,往往是获取数据较难
首先前端,只需要一个div,用ref指定名称,定好宽高,就ok,div多大,图就会自适应多大
<div>
<h1 style="display: inline-block;width: 800px">商品分类柱状图</h1>
<h1 style="display: inline-block;width: 400px">商品类型占比图</h1>
<--柱状图div-->
<div style="width: 600px;height: 600px;float: left" ref="zhu"></div>
<--饼状图div-->
<div style="width: 600px;height: 600px;float: right" ref="bing"></div>
</div>
然后写一个方法用$refs指定div设置图表
//柱状图
getZhu(){
const Echarst=echarts.init(this.$refs.zhu)
Echarst.setOption(
{
xAxis: {
type: 'category',
data: this.zhuData1
},
yAxis: {
type: 'value'
},
series: [
{
data: this.zhuData2,
type: 'bar'
}
]
}
)
},
//饼状图
getBing(){
const Echarts=echarts.init(this.$refs.bing)
Echarts.setOption({
series:[
{
name: 'Access From',
type: 'pie',
radius: '50%',
label: {show: true},
data: this.bingData
},
]
})
}
上面用到的data数据,我们也创建一下,饼状图需要一个数组,柱状图需要两个
data(){
return{
bingData:[],
zhuData1:[],
zhuData2:[],
}
},
最后就是获取这些数据,也可以写si数据试一下能跑起来不,反正就是要获取到以下结构的数据:
data(){
return{
bingData:[
{name:"水果类",value:6},
{name:"零食类",value:3},
{name:"蔬菜类",value:9},
],
zhuData1:["水果类","零食类","蔬菜类"],
zhuData2:[6,3,9],
}
},
我是怎么获取的这里也展示一下,
后端代码:
在typeController只要两个方法:
@CrossOrigin
@RequestMapping("/types")
@RestController
public class TypeController {
@GetMapping
public Result findAll(){
//获取所有type
return service.findAll();
}
@GetMapping("/count")
public Result getTypeCount(){
//获取每个类型有多少商品count
return service.getTypeCount();
}
}
typeService,相信大家都会写:
public interface TypeService extends IService<Type> {
Result findAll();
Result getTypeCount();
}
@Service
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService {
@Override
public Result findAll() {
return Result.ok(list());
}
@Override
public Result getTypeCount() {
return Result.ok(typeMapper.getTypeCount());
}
}
mapper层只有一个方法
@Mapper
public interface TypeMapper extends BaseMapper<Type>{
List<Type> getTypeCount();
}
typeMapper.xml 需要自己写sql语句了
<?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.example.mapper.TypeMapper">
<select id="getTypeCount" resultType="Type">
select t.type_name typeName,count(*) `count`
from goods g
inner join `type` t on t.tid=g.tid
group by type_name
</select>
</mapper>
yml的配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/goods?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT-8&useSSL=false
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
server:
port: 8088
servlet:
context-path: /goods
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
type-aliases-package: com.example.entity
global-config:
db-config:
id-type: auto
mapper-locations: classpath:mapper/*.xml
前端的this.baseUrl也记得换成相对应的路径(http://localhost:8088/goods)
最后启动前端后端,访问
http://localhost:8088