1.gin
很简单,写个api接口
package main
import (
"fmt"
"log"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello golang http!")
}
func main() {
http.HandleFunc("/home", index)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
2.vue
搭建vue环境,两个单页面
image.png
main.js
需要使用路由和axios
import Vue from 'vue'
import App from './App.vue'
import router from '@/router'
import axios from 'axios'
Vue.config.productionTip = false
Vue.prototype.$axios = axios
new Vue({
router,
render: h => h(App),
}).$mount('#app')
vue.config.js
需要配置跨域的代理
module.exports = {
publicPath: '/',
outputDir: 'dist',
devServer: {
open: true,
host: 'localhost',
port: '8081',
proxy: {
'/api': {
target: 'http://localhost:9090', // 要请求的地址
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
}
};
router.js
两个页面的路由
import Vue from 'vue'
import Router from 'vue-router'
import Home from './components/Home.vue'
import Abc from './components/Abc.vue'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/abc',
name: 'abc',
component: Abc
}
]
})
app.js
使用路由
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
abc.vue
需要调用后台的api
<template>
<div class="hello">
<h1>{{ msg }}</h1>
<p>
gogogo,{{ msg }}
</p>
</div>
</template>
<script>
export default {
name: 'Abc',
data() {
return {
msg: ''
}
},
created() {
this.$axios.get('/api/home').then(result=>{
this.msg = result.data;
})
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
网友评论