同步更新的github地址:https://github.com/nds15763/ginMall
看了一位老哥写的《前后分离Vue+Gin(go)总结》以后有种自己搭一份的想法,结合最近找工作比较闲,就准备自己写一份商城源码。
一、先来实现前端部分第一步搭建Vue框架。Vue我也是第一次接触,看了半天多的文档才有了大概的了解。先不过多考虑前端的实现,首先考虑一下前后台沟通的问题。
用vue-cli搭建一个新框架,在Helloworld.vue 或者新建一个模板页。
老哥的文档中写到,他推荐使用axios插件代替jquery来和后台做交互。那么我也按照他的思路安装一个axios插件,写一个跟后台通讯的Get请求。
<template>
<div>
<p>{{namee}}</p>
<p>请求状态:{{status}}</p>
<p>请求之后的数据:{{show}}</p>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return{
namee: 'Cart1321',
show: '',
status: ''
}
},mounted(){
axios.get("http://localhost:8081"+'/FPList')
.then((response)=>{
console.log(response.data);
this.status = response.status;
this.show = response.data;
})
.catch((error)=> {
console.log(error);
});
}
}
</script>
二、然后来搭建后台框架,老哥说的是用Gin框架来搭建,并且用cors中间件来解决跨域访问问题,咱们也先来搭建一个简单的框架。
main.go
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.Run(":8081")
}
router.go
package main
import (
"net/http"
"./FPList"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
func RouterInit(router *gin.Engine) {
router.Use(cors.Default())
router.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "It works On 8081")
})
router.GET("/FPList", FPList.GetList)
}
FPList.go
package FPList
import "github.com/gin-gonic/gin"
type itemList struct {
ID int
Sort int
Name string
Status string
Forums []forumsList
}
type forumsList struct {
ID int
Fgroup int
Sort int
Name string
ShowName string
Msg string
Interval int
CreatedAt string
UpdateAt string
Status string
}
func GetList(c *gin.Context) {
flist := []forumsList{
forumsList{
ID: 3,
Fgroup: 4,
Sort: 1,
Name: "每日好货3",
ShowName: "",
Msg: "msg",
Interval: 1,
CreatedAt: "2018-07-20 15:49:28",
UpdateAt: "2018-07-20 15:49:28",
Status: "n",
},
...随便写内容
}
rtList := itemList{
ID: 1,
Sort: 1,
Name: "每日好货D",
Status: "n",
}
rtList.Forums = flist
c.JSON(0, rtList)
}
在浏览器里输入localhost:8081/FPList,可以看到刚才自己定义的Json串,知道后台算是成功了。
{"ID":1,"Sort":1,"Name":"每日好货D","Status":"n","Forums":[{"ID":3,"Fgroup":4,"Sort":1,"Name":"每日好货3","ShowName":"","Msg":"msg","Interval":1,"CreatedAt":"2018-07-20 15:49:28","UpdateAt":"2018-07-20 15:49:28","Status":"n"},{"ID":5,"Fgroup":4,"Sort":1,"Name":"每日好货5","ShowName":"","Msg":"msg","Interval":1,"CreatedAt":"2018-07-20 15:49:28","UpdateAt":"2018-07-20 15:49:28","Status":"n"},{"ID":2,"Fgroup":4,"Sort":1,"Name":"每日好货2","ShowName":"","Msg":"msg","Interval":1,"CreatedAt":"2018-07-20 15:49:28","UpdateAt":"2018-07-20 15:49:28","Status":"n"},{"ID":4,"Fgroup":4,"Sort":1,"Name":"每日好货4","ShowName":"","Msg":"msg","Interval":1,"CreatedAt":"2018-07-20 15:49:28","UpdateAt":"2018-07-20 15:49:28","Status":"n"}]}
此时再打开前端页面,可以看到后台返回的结果已经显示在页面了。