本篇将使用echarts框架进行柱状图和折线图绘制。
目录
1.绘制效果
2.安装echarts
3.前端代码
4.后端代码
1.绘制效果
2.安装echarts
// 安装echarts版本4
npm i -D echarts@4
3.前端代码
src/api/api.js
//业务服务调用接口封装import service from '../service.js'
//npm i qs -D
import qs from 'qs'//登录接口
export function login(data) {return service({method: 'post',url: '/login',data})
}//学生信息查询接口
export function students(params) {return service({method: 'get',url: '/api/students',params})
}//删除学生信息
export function delstudentsbyid(id) {return service({method: 'get',//此处应用模板字符串传参url: `/api/students/del?id=${id}`})
}export function delstudentsbyreqid(id) {return service({method: 'get',//此处应用模板字符串传参url: `/api/students/del/${id}`})
}export function addStudent(data) {//data = qs.stringify(data)return service({method: 'post',url: '/api/info',data})
}export function updateStudent(data) {return service({method: 'post',url: '/api/updateinfo',data})
}export function getInfo() {return service({method: 'get',url: '/api/getinfo'})
}export function delinfo(id) {return service({method: 'get',//此处应用模板字符串传参url: `/api/info/del/id=${id}`})
}export function dataview(id) {return service({method: 'get',url: '/api/data/dataview'})
}
src/components/common/dataanalyse/DataView.vue
<template><div class="data-view"><el-card><div id="main1"></div></el-card><el-card><div id="main2"></div></el-card></div>
</template><script>
import { dataview } from '@/api/api.js'export default {data() {return {name: ""}},created() {//http获取服务端数据,huizhe 折线图dataview().then(res => {console.log(res)if (200 === res.data.status) {let {legend, xAxis, series} = res.data.datathis.draw(legend, xAxis, series)}})},mounted() {//初始化实例let myChart = this.$echarts.init(document.getElementById('main1'))myChart.setOption({title: {text: '大佬学vue分数'},tooltip: {},xAxis: {data: ['张三', '李四', '王五', '赵六']},yAxis: {},series: [{name: '人数',// bar: 柱状图 line: 折线图type: 'bar',data: [90, 100, 85, 70]}]})},methods: {draw(legend, xAxis, series) {let myChart1 = this.$echarts.init(document.getElementById('main2'))let option = {title: {text: "会话量"},tooltip: {trigger: 'axis'},legend: {data: legend},xAxis: {type: 'category',data: xAxis},yAxis: {type: 'value'},series: series}myChart1.setOption(option)}}
}
</script><style lang='scss'>
.data-view {width: 100%;display: flex;justify-content: space-between;.el-card {width: 50%;#main1, #main2 {height: 500px;}}
}
</style>
4.后端代码
server.go
package mainimport ("main/controller""net/http""github.com/gin-contrib/cors""github.com/gin-gonic/gin"
)/*
// 错误: server.go:4:2: package main/controller is not in GOROOT (/home/tiger/go/go/src/main/controller)
go mod init main//错误: server.go:7:2: no required module provides package github.com/gin-gonic/gin; to add it:
go get github.com/gin-gonic/gin//处理跨域框架
go get github.com/gin-contrib/cors
*//*
当客户端(尤其是基于 Web 的客户端)想要访问 API 时,服务器会决定允许哪些客户端发送请求。这是通过使用称为 CORS 来完成的,它代表跨源资源共享。
跨域资源共享 (CORS) 是一种机制,允许从提供第一个资源的域之外的另一个域请求网页上的受限资源。
*/func CrosHandler() gin.HandlerFunc {return func(context *gin.Context) {context.Writer.Header().Set("Access-Control-Allow-Origin", "*")context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域context.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE,UPDATE")context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")context.Header("Access-Control-Max-Age", "172800")context.Header("Access-Control-Allow-Credentials", "true")context.Set("content-type", "application/json") //设置返回格式是json//处理请求context.Next()}
}// http://127.0.0.1:8181/ping
// http://127.0.0.1:8181/index
func main() {r := gin.Default()// 设置全局跨域访问//r.Use(CrosHandler())//cors处理跨域corsConfig := cors.DefaultConfig()corsConfig.AllowCredentials = truecorsConfig.AllowHeaders = []string{"content-type", "Origin", "token", "username"}corsConfig.AllowOrigins = []string{"http://localhost:8080", "http://localhost:8081"}corsConfig.AllowMethods = []string{"POST", "GET", "OPTIONS", "PUT", "DELETE", "UPDATE"}r.Use(cors.New(corsConfig))//r.Use(cors.Default())// 返回一个json数据r.GET("/ping", func(c *gin.Context) {c.JSON(200, gin.H{"message": "pong","num": 888,})})// 返回一个html页面r.LoadHTMLGlob("templates/*")r.GET("/index", func(c *gin.Context) {c.HTML(http.StatusOK, "index.html", nil)})r.POST("/login", controller.LoginPost)r.POST("/formlogin", controller.FormLoginPost)r.POST("/upload", controller.UploadFile)r.GET("/api/students", controller.GetStudentList)r.GET("/api/students/del", controller.DelStudent)r.GET("/api/students/del/:id", controller.DelStudentByReq)r.POST("/api/info", controller.AddStudent)r.GET("/api/getinfo", controller.GetInfo)r.POST("api/updateinfo", controller.UpdateStudent)r.GET("/api/info/del/:id", controller.DelIfo)r.GET("api/works", controller.Works)r.GET("/api/data/dataview", controller.DataView)//r.Run() // <===> r.Run(":8080") 监听并在 0.0.0.0:8080 上启动服务r.Run(":8181")
}
controller/dataview.go
package controllerimport ("net/http""github.com/gin-gonic/gin"
)/*
//嵌套json举例
type Person struct {Name string `json:"name"`Age int `json:"age"`Address struct {Street string `json:"street"`City string `json:"city"`} `json:"address"`
}person := Person{"张三", 20, struct {Street string `json:"street"`City string `json:"city"`} {"北京路", "广州市",}
}
c.JSON(200, person)
*//*
// 给前端发送如下数据
{"legend": ["技术总监", "产品经理", "后端开发", "前端开发", "运维/测试"],"xAxis": ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],"series": [{"name": "技术总监","type": "line","stack": "总量","data": [80, 83, 84, 40, 44, 11, 12]},{"name": "产品经理","type": "line","stack": "总量","data": [66, 34, 39, 42, 45, 20, 30]},{"name": "后端开发","type": "line","stack": "总量","data": [66, 65, 59, 44, 33, 10, 20]},{"name": "前端开发","type": "line","stack": "总量","data": [33, 33, 44, 55, 55, 11, 23]},{"name": "运维/测试","type": "line","stack": "总量","data": [67, 45, 32, 40, 27, 11, 59]},]
}
*/type Response struct {Status int `json:"status"`Msg string `json:"msg"`Data interface{} `json:"data"`
}type TSeries struct {Name string `json:"name"`Type string `json:"type"`Stack string `json:"stack"`Data []int `json:"data"`
}type DataItem struct {Legend []string `json:"legend"`XAxis []string `json:"xAxis"`Series []TSeries `json:"series"`
}var dataItem = DataItem{Legend: []string{"技术总监", "产品经理", "后端开发", "前端开发", "运维/测试"},XAxis: []string{"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"},Series: []TSeries{{Name: "技术总监",Type: "line",Stack: "总量",Data: []int{80, 83, 84, 40, 44, 11, 12},},{Name: "产品经理",Type: "line",Stack: "总量",Data: []int{66, 34, 39, 42, 45, 20, 30},},{Name: "后端开发",Type: "line",Stack: "总量",Data: []int{66, 65, 59, 44, 33, 10, 20},},{Name: "前端开发",Type: "line",Stack: "总量",Data: []int{33, 33, 44, 55, 55, 11, 23},},{Name: "运维/测试",Type: "line",Stack: "总量",Data: []int{67, 45, 32, 40, 27, 11, 59},},},
}var response = Response{200,"获取数据成功",dataItem,
}// GET请求 http://127.0.0.1:8181/api/data/dataview
func DataView(ctx *gin.Context) {ctx.JSON(http.StatusOK, response)
}