Vue_02 Axios异步请求详解

1. Axios 基本使用

1.1 引言

Axios 是一个异步请求技术,核心作用就是用来在页面中发送异步请求,并获取对应数据在页面中渲染 页面局部更新技术 Ajax

在这里插入图片描述

1.2 Axios 的下载

中文网站:https://www.kancloud.cn/yunye/axios/234845

安装: https://unpkg.com/axios/dist/axios.min.js

1.3 GET方式的请求

	  //发送GET方式请求
    axios.get("http://localhost:8989/user/findAll?name=xiaochen").then(function(response){
    
    
        console.log(response.data);
    }).catch(function(err){
    
    
        console.log(err);
    });

1.4 POST方式请求

		//发送POST方式请求
    axios.post("http://localhost:8989/user/save",{
    
    
        username:"xiaochen",
        age:23,
        email:"[email protected]",
        phone:13260426185
    }).then(function(response){
    
    
        console.log(response.data);
    }).catch(function(err){
    
    
        console.log(err);
    });

1.5 axios并发请求

并发请求: 将多个请求在同一时刻发送到后端服务接口,最后在集中处理每个请求的响应结果

function getUserAccount() {
    
    
  return axios.get('/user/12345');
}

function getUserPermissions() {
    
    
  return axios.get('/user/12345/permissions');
}

axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    
    
    // 两个请求现在都执行完成
}));

1.6 put方式的请求

   axios.put("http://localhost:8080/test",{
    
    name:"松崎乡",age:"21"}).then(function (response) {
    
    
        console.log(response);
    }).catch(function (error) {
    
    
        console.log(error);
    });

1.7 path方式的请求

 axios.path("http://localhost:8080/test",{
    
    name:"松崎乡",age:"21"}).then(function (response) {
    
    
        console.log(response);
    }).catch(function (error) {
    
    
        console.log(error);
    });

1.8 delete方式的请求(同理)

 axios.delete("url?id=21").then(function (response) {
    
    

    }).catch(function (error) {
    
    

    });

1.9 拦截器

拦截器:请求拦截器 + 响应拦截器
在这里插入图片描述

配置一个拦截器

<script>
    /*全局配置axios,所有异步请求由其发出!*/
    let instance = axios.create({
    
    
        baseURL: 'http://localhost:8080/',
        timeout: 5000 ,
    });

    /*添加拦截器:请求拦截器 | 响应拦截器*/
    instance.interceptors.request.use(function (config) {
    
    

        console.log("进入请求拦截器");
        if (config.url.indexOf("?") == -1){
    
      //url中没有?拼接的时候需要添加问号
            config.url+="?token=1234"
        }else{
    
    
            config.url+="&token=1234" ;
        }

        return config ;
    }) ;

    instance.interceptors.response.use(function (response) {
    
    
        console.log("进入响应拦截器");
            response.data = "xxx" ;  //修改响应结果

        if (response.status!=200){
    
       //同一处理异常
            console.log("相应出错");
        }
        return response ;
    });

    instance.get("/demo?name=qxsong&age=21").then(function (response) {
    
    
        console.log(response.data);

    });
    /*.catch(function (error) {
        console.log(error);
    })*/

 /*   instance.get("/test1").then(function (response) {
        console.log(response.data);
    }).catch(function () {

    })*/

</script>

案例:员工信息管理

我们通过基础指令和Axios+Bootstrap,结合我们的SpringBoot快速打通并实现一个简单的CRUD

实现效果
在这里插入图片描述

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>员工列表管理页面</title>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
</head>
<body>
        <div id="app">
            <div class="container">
                <!--栅格系统-->
                <div class="row">
                   <div class="col-sm-12" style="text-align: center">
                       <h1>{
   
   {msg}}</h1>
                   </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <button class="btn btn-primary btn-sm" style=" margin-bottom: 20px ; margin-left: 0px " @click="addEmp">新增员工</button>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <table class="table table-striped table-bordered table-hover" align="center"  style="width: 100%">
                            <tr style="text-align: center">
                                <th>编号</th>
                                <th>姓名</th>
                                <th>年龄</th>
                                <th>工资</th>
                                <th>操作</th>
                            </tr>
                            <tr v-for="emp in emps" :key="emp.id" align="center">
                                <td>{
   
   {emp.id}}</td>
                                <td>{
   
   {emp.name}}</td>
                                <td>{
   
   {emp.age}}</td>
                                <td>{
   
   {emp.salary}}</td>
                                <td><a href="#" @click.prevent="delEmp(emp.id)" class="btn btn-primary btn-sm">删除</a>&nbsp&nbsp&nbsp
                                    <a href="#" @click.prevent="updEmp(emp.id)" class="btn btn-danger btn-sm">修改</a></td>
                            </tr>
                        </table>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <form action="#">
                            <!-- 编号:<input type="text" v-model="emp.id"> <br>-->
                            <div class="form-group">
                                <label>姓名:</label>
                                <input type="text" class="form-control" v-model="emp.name">
                            </div>
                            <div class="form-group">
                                <label>年龄:</label>
                                <input type="text"  class="form-control" v-model="emp.age">
                            </div>
                            <div class="form-group">
                                <label> 工资:</label>
                                <input type="text" class="form-control"  v-model="emp.salary">
                            </div>
                            <input type="button" class="btn btn-success btn-sm btn-block" value="提交信息" @click="saveOrEdit">
                        </form>
                    </div>
                </div>

            </div>

        </div>
</body>
</html>
<script src="js/vue.js"></script>
<script src="js/axios.min.js"></script>
<script>

    //配置全局axios
    let instance = axios.create({
      
      
        baseURL:"http://localhost:8080" ,
        timeout:5000
    });

    //响应拦截器 和 请求拦截器
    instance.interceptors.response.use(function (response) {
      
      
        return response ;
    },function (error) {
      
      
        alert("后端服务出错了,请稍后再试!")    //全局处理错误!
    });

     let app = new Vue({
      
      
         el:"#app" ,
         data:{
      
      
             msg:"员工信息列表" ,
             emps:[],
             emp:{
      
      },
         },
         methods:{
      
      
             addEmp:function(){
      
      
                 this.emp = [] ;
             },
             delEmp:function (id) {
      
      
                 if(window.confirm("您确定要删除吗?")){
      
      
                     let _this = this ;
                     instance.delete("/emp/"+id).then(function (response) {
      
      

                         _this.findAll() ;  //删除成功后,再次查询全部列表

                     })
                 }
             },
             findAll:function () {
      
      
            //异步请求方法中的this不是vue实例一定要注意,箭头函数的this就是父方法的this
                 instance.get("/emp").then( response => {
      
      
                     this.emps = response.data ;
                 })
             },
             saveOrEdit:function () {
      
      
                 let _this = this ;
                 if (_this.emp.name && _this.emp.age && _this.emp.salary){
      
      
                     instance.post("/emp",this.emp).then(function (response) {
      
         //带着员工信息去发送异步请求
                         alert("保存信息成功!")
                         _this.emp= {
      
      } ;
                         _this.findAll() ;
                     })
                 }else{
      
      
                     alert("请检查添加用户的信息,不能为空")
                 }
             },
             updEmp:function (id) {
      
      
                 let _this = this ;
                 instance.get("/emp/"+id).then(function (response) {
      
      
                        _this.emp = response.data ;
                 })
             }
         },
         computed:{
      
      

         },
         created(){
      
      
                this.findAll() ;
         }

     });
</script>

参考视频:编程不良人Vue全家桶

猜你喜欢

转载自blog.csdn.net/m0_46571920/article/details/121350801