vue与服务端交互

vue与服务端交互简单示例


前面我们在使用vue的时候,都是对客户端浏览器进行渲染,现在我们使用vue来和服务端进行简单的交互,客户端使用的技术是axios,服务端使用的是gin框架。

编写客户端代码

# 首先新建一个文件夹,然后打开cmd,使用vue-cli新建一个项目
vue create [项目名]
# 然后下载一些基本要用到的库
cnpm install axios --save  # axios库

cnpm install vue-router@3.2.0 # vue-router库 (这个版本对应vue2)

main.js

在main.js中我们需要创建一个vue对象,然后设置一些全局属性:

// 导入需要的库
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'

// 创建axios对象,设置全局服务端URL
// 然后把axios对象设置为vue实例的全局属性,这样就不用在每个组件中单独导入axios了
const instance = axios.create({
  baseURL: "/api",
})
Vue.prototype.$axios = instance;

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

vue.config.js

这个文件主要管项目配置,这里我只设置一个允许跨域:

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    proxy: {  //配置跨域
      '/api': {
        target: 'http://127.0.0.1:9090/',  //这里后台的地址模拟的;应该填写你们真实的后台接口
        changOrigin: true,  //允许跨域
        pathRewrite: {
          /* 重写路径,当我们在浏览器中看到请求的地址为:http://localhost:8080/hello 时
            实际上访问的地址是:http://127.0.0.1:9090/core/getData/hello,因为重写了 /api
           */
          '^/api': '' 
        }
      },
    }
  },
})

HelloWorld.vue

在componment目录下创建一个HelloWorld.vue组件

<template>
  <div class="hello">
    <h1>{{msg}}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      msg:null,
    }
  },
  // 加载页面完成的时候 就向服务端发送请求
  // 然后将返回的数据渲染到页面上
  mounted() {
    this.$axios.get("/hello").then((res) => {
      this.msg = res.data.message;
      console.log(res.data.message);
    }).catch(function() {

    })
  }
}
</script>

router.js

编写前端路由:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)
const routes = [
    {
        path: '/helloworld',
        name: 'helloworld',
        component: () => import('./components/HelloWorld.vue')
    }
    
]

const router = new VueRouter({
    mode: 'history',
    routes
})

export default router

App.vue

修改挂载的根组件,在router.js中定义的组件在访问的时候都会被放在这个根组件中,根组件上要加入<router-view></router-view>,不然子组件不会显示。

<template>
    <div id="app">
        <router-view></router-view>
    </div>
</template>

<script>
export default {
    name: "app",
}
</script>
<style>
    html, body {
        margin: 0;
        padding: 0;
    }
</style>

编写服务端代码

# 安装gin
go get -u github.com/gin-gonic/gin
package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func main() {
	r := gin.Default()
	r.GET("/hello", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"message" : "success",
		})
	})
	r.Run(":9090")
}

测试

在这里插入图片描述

成功获取到服务端发来的数据,并渲染到页面上。


  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值