Vue 异步请求

Vue 异步请求

Vue 中使用 axios 进行网络请求,使用起来和 jQuery 中的 $.get$.post 功能类似。

安装依赖:cnpm install --save axios

1. get 请求方式

给定服务器控制器代码,可以接收 name 和 age 参数,设置到 Map 中并返回。

注意:控制器上有跨域注解。前后端分离都是跨域请求。且端口不能设置 8080 端口,避免端口冲突。

<template>
    <div id="app">
        <div>用户名:{{stu.name}}</div>
        <div>年龄:{{stu.age}}</div>
    </div>
</template>

<script>
    import axios from "axios"
    export default {
        name: 'App',
        data(){
            return{
                stu:{
                    "name":null,
                    "age":null,
                }
            }
        },
        mounted(){
            //页面加载事件
            axios.get("http://localhost:8181/index?name=zhangsan&age=18")
                .then(res => {
                    console.log(res.data);
                    this.stu = res.data;
                })
                .catch(error => {
                    console.log(error);
                })
        }
    }
</script>

2. post 请求方式

POST 也支持 URL 重写方式传参,即通过 ? 和 & 传递参数,如果使用这种方式传参必须要结合 querystring 使用。

<template>
    <div id="app">
        发起请求获取到的结果:<span>{{name}},{{age}}</span>
    </div>
    <router-view/>
</template>

<script>

    import axios from "axios"
    import qstring from "querystring"
    export default {
        name: 'App',
        data(){
            return{
                name:null,
                age: null,
            }
        },
        mounted(){
            // 页面加载事件
            axios.post("http://localhost:8181/index", qstring.stringify({
                    name : "张三",
                    age: 23
            })) //处理的结果是 name=张三&age=23
            .then(res => {
                console.log(res.data);
                this.name = res.data.name;
                this.age = res.data.age;
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
</script>

后端的业务代码:

@RestController
@CrossOrigin  //跨域注解
public class TestController {

    @RequestMapping("/index")
    public Map<String, Object> index(@Param("name") String name,@Param("age") Integer age){
        Map<String, Object> result = new HashMap<>();
        result.put("name", name);
        result.put("age", age);
        return result;
    }
}

3. axios 全局设置

如果使用上面的这种方式,需要在每个页面中都导入 axios,更简便的方式是全局绑定 axios。

修改 main.js

import { createApp } from 'vue'
import App from './App.vue'

//导入./router/index文件里面配置好的路由
import router from './router/index'
import axios from "axios"
import qstring from "querystring"

//全局Vue对象
const Vue=createApp(App);
// 设置axios、qstring全局
Vue.config.globalProperties.$axios=axios;
Vue.config.globalProperties.$qstring=qstring;

Vue.use(router).mount('#app');

页面中的写法:在任何页面中都可以直接使用 this.$axiosthis.$qstring 进行设置。

<template>
    <div id="app">
        发起请求获取到的结果:<span>{{name}},{{age}}</span>
    </div>
    <router-view/>
</template>

<script>
    export default {
        name: 'App',
        data(){
            return{
                name:null,
                age: null,
            }
        },
        mounted(){
            // 页面加载事件
            this.$axios.post("/api/index", this.$qstring.stringify({
                    name: "张三",
                    age: 15
            }))
            .then(res => {
                console.log(res.data);
                this.name = res.data.name;
                this.age = res.data.age;
            })
            .catch(error => {
                console.log(error);
            })
        }
    }
</script>

4. 请求代理

   在 Vue 中发起网络请求时 URL 都使用的是完整的 URL,可以把公共 URL 提出来,提出后发起网络请求时,URL 只写路径部分,省略协议、IP 和端口。

   如果没有请求代理,每次在浏览器开发者工具看见真实请求服务器地址,这样话就把服务器暴露给客户端了。使用代理后只能看见代理前请求,保护真实服务器地址。

在项目根路径(不是src)下新建 vue.config.js:

这个配置文件操作完成后必须重启

const { defineConfig } = require('@vue/cli-service');
module.exports = defineConfig({
    transpileDependencies: true,
    lintOnSave:false,
    //配置请求代理
    devServer: {
        proxy: {
            //当请求Vue项目路径都以/api开头时,转发给下面
            '/api': {
                //服务器URL
                target: "http://localhost:8181/",
                ws: true,
                pathRewrite: {
                    //把路径中的api去掉
                    '^/api': ''
                },
                changeOrigin: true
            }
        }
    }
});

发起请求时可以使用 /api/xxx 的形式:

mounted(){
    // //页面加载事件
    axios.get("/api/index?name=zhangsan&age=18")
        .then(res => {
        console.log(res.data);
        this.name = res.data.name;
        this.age = res.data.age;
    })
        .catch(error => {
        console.log(error);
    })
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值