axios的简单使用

既然官方已经说了不在维护vue-resource,那我们就看看axios是怎么使用的..........

1)get方法的使用

axios.get
 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios的初步使用</title>
    <script src="../lib/vue.js"></script>
    <script src="../lib/axios.min.js"></script>
</head>
<body>
   <div id="app">
       <my-f1></my-f1>
   </div>
</body>
</html>
<script>
    const c1={
        template:`
            <div v-if="userList.length">
                  <ul>
                    <li v-for="item in userList">{{item.id}}</li>
                  </ul>
            </div>
        `,
        props:{},
        data(){
            return {
                userList:['fd','rr','tt'],
            }
        },
        mounted(){
            this.getList();
        },
        computed:{
             user(){
                return this.usersList;
             }
        },
        methods:{
            getList(){
                const self=this;
                axios.get('../data/a1.php',{params:{
                    id:2
                }}).then(function(res){
                    self.userList=res.data;
                }).catch(function(res){
                    console.log(res);
                });
            },
        }
    };
    const myVue = new Vue({
        el:'#app',
        components:{
            myF1:c1
        },
    });
</script>

a1.php

<?php
  header("Content-Type:application/json;charset=UTF8");
  $myDB=  new PDO('mysql:host=127.0.0.1;dbname=axiox;port=3307','root','');
  $id=$_GET['id'];
 //  $fname=$_POST['firstname'];
  // $lname=$_POST['lastname'];
  // $body = @file_get_contents('php://input');
 // echo $fname ;
  if($myDB){
     $res= $myDB->query("select * from stu");

     while($row = $res->fetch( PDO::FETCH_ASSOC)){
        // print_r($row);
        $arr[]=$row;
     }
  }
  else{
    die("fali");
  }
 // json_encode($arr);
  print_r( json_encode($arr));
?>

以上很简单的一个例子。。。。

我们注意一下请求头的content-type

 

2)使用post请求

axios.post
当你使用post请求的时候,好像会有一点问题。。。。。
axios.post('../data/a1.php', {//后端就不能使用$_post['']接受参数了,后端要接受请求主体
name:'士大夫', age:33 }) .then(function(res){ self.userList=res.data; }) .catch(function(res){ console.log(res); });

php:

$fname=$_POST['name'];

 

结果:

好像获取不到请求传递的值......

但是办法还是有的,这个时候我们可以在后端(这里使用的是php),来获取整个请求主体....

$body = @file_get_contents('php://input');

但还是很奇怪,为啥????

看看官方的解释.................

然后我就试试....

    getList(){
            const self=this;        //这里我们不修改请求头,而是修改 userService(手动将post请求参数变为get请求形式,后端可以使用$_POST['参数名'],接受参数)
            let param = new URLSearchParams();
            param.append("firstname", "Fred");
            param.append("lastname", "Flintstone");

            axios.post('../data/a1.php',param)
            .then(function(res){
                self.userList=res.data;
            })
            .catch(function(res){
                console.log(res);
            });
            
        },

php接受参数;(很明显我前端做了参数处理

$fname=$_POST['firstname'];
echo $fname;

 

很明显的发现我们现在的请求方式变为:

Content-Type:application/x-www-form-urlencoded;charset=UTF-8
 
问题来了,我不想使用这个 let param = new URLSearchParams();但是又想发送我的post请求怎么办??
 
那么就让后端做处理了
前端:(不做处理)
axios.post('../data/a2.php', {
    name:'tom',
    age:33,
    id:'wodo id shi 222'
})
.then(function(res){
    self.userList=res.data;
})
.catch(function(res){
     console.log(res);
});

后端:

  $body = @file_get_contents('php://input');//接受整个请求主体
  $body=json_decode($body)  ;//反序列化
  $id=$body->id;//获取欲取参数
  echo $id;

进一步拓展:

表单提交enctype参数详解之:application/x-www-form-urlencode和multipart/form-data

 https://www.lvtao.net/dev/1179.html

 

3)axios.all的使用
我们可能要在多个请求完成之后,在进行下一步操作,这里涉及到一个异步问题,但是axios.all就可以帮我们轻松解决这个问题。。。
我本以为是这样,但是结果好像不是这样。。。。。。。。。。。。。。。。。。。
【可能是我理解有误,如果有人能指正,很感激。。】
先看看我的例子
<script>
    const c1={
        template:`
    <div v-if="userList.length">
            <ul>
            <li v-for="item in userList">{{item.id}}</li>
            <p>this is  tea ifno :
                <table>
                  <tr>
                    <td>id</td>
                    <td>name</td>
                    <td>salary</td>
                    <td>address</td>
                  </tr>
                    <tr>
                        <td>{{tea.id}}</td>
                        <td>{{tea.name}}</td>
                        <td>{{tea.salary}}</td>
                        <td>{{tea.address}}</td>
                    </tr>
                </table>
            </p>
    </ul>
    </div>
    `,
    props:{},
    data(){
        return {
            userList:['fd','rr','tt'],
            tea:{},
        }

    },
    mounted(){
        axios.all([this.getList(), this.getTea()])
                .then(axios.spread(function (acct, perms) {
                     console.log("all request finished");
                     console.log(acct);
                }));
    },
    methods:{
        getList(){
            const self=this;
             axios.get('../data/a1.php')
             .then(function(res){
             self.userList=res.data;
             })
             .catch(function(res){
             console.log(res);
             });
        },

        //第二个请求
        getTea(){
            const self=this;
            axios.get('../data/a2.php',{
              params:{id:2,}
                //name:'fafa'
            }).then(function(res){
                self.tea =res.data[0];
            });
        }
    }
};

const myVue = new Vue({
    el:'#app',
    components:{
        myF1:c1
    },
});
</script>

我在php文件中做了一个延时处理。

a2.php

<?php
  $conn=mysqli_connect('127.0.0.1','root','','axiox',3307);
  $sql="SET NAMES UTF8";
  mysqli_query($conn,$sql);

  // $body = @file_get_contents('php://input');
  //$body=json_decode($body)  ;

  //$id=$body->id;


  // $id=$_POST['id'];

  $id=$_GET['id'];
  $sql="SELECT * FROM tea WHERE id=$id";
  $result=mysqli_query($conn,$sql);
  $list=mysqli_fetch_assoc($result);
  $arr=[];
  $arr[]=$list;
  sleep(5);
  echo json_encode($arr);
 // print_r( json_encode($res));
?>

a1.php

<?php
  // header("Content-Type:application/json;charset=UTF8");
  // header("Content-Type:application/x-www-form-urlencoded;charset=UTF8");
  $myDB=  new PDO('mysql:host=127.0.0.1;dbname=axiox;port=3307','root','');

  //$id=$_GET['id'];
  //  $lname=$_POST['lastname'];
  //$body = @file_get_contents('php://input');
  //$fname=$_POST['firstname'];
  //echo $body ;
  // echo $fname;

  if($myDB){
     $res= $myDB->query("select * from stu");

     while($row = $res->fetch( PDO::FETCH_ASSOC)){
        // print_r($row);
        $arr[]=$row;
     }
  }
  else{
    die("fali");
  }
  sleep(5);
  print_r( json_encode($arr));

?>

我本以为在js里面axios.all的两个请求都执行问之后才执行 console.log("all request finished");

但是结果不是,而是先输出了这句话,,,,,毁三观

 

4)axios({.....})的使用(比较简单,不具体说明了)
 getList(){
            const self=this;
            axios({
                method:'get',
                url:'../data/a2.php',
               // responseType:'stream',
                params:{
                    id:2,
                }
            })
            .then(function(res) {
                    self.tea=res.data[0];
            });
        },

5)axios.create的使用,主要用于自定义请求配置。

详情看文档,,,,,

 

 6)拦截器的使用(主要用于在请求等待时候做一些优化处理)

基本语法:
axios.interceptors.request.use(function (config) {
// Do something before request is sent console.log("请求之前"); return config;//这句话不能丢 }, function (error) { // Do something with request error console.log("对错误deal"); return Promise.reject(error); })

demo:

创建一个组件

 const c1={
        template:`
            <div>
              <p>this is a  demo </p>
                <table>
                    <tr>
                        <td>id</td>
                        <td>name</td>
                        <td>salary</td>
                        <td>address</td>
                    </tr>
                    <tr>
                        <td>{{tea.id}}</td>
                        <td>{{tea.name}}</td>
                        <td>{{tea.salary}}</td>
                        <td>{{tea.address}}</td>
                    </tr>
                </table>
            </div>`,
            props:{},
            data(){
                return {
                    tea:{
                        id:1,
                        name:'eee',
                        salary:1233,
                        address:'中国天安门'
                    },
                }
            },
            methods:{
                getList(){
                    const self=this;
                    self.createInter();
                    axios.get('../data/a4.php',{///a4.php做了延时处理
                        params:{
                            id:2
                        }
                    }).then(function(res){
                        self.tea=res.data[0];
                    },function(err){
                        console.log(err);
                    });
                },
                createInter(){
                  const interOne=axios.interceptors.request.use(function (config) {
                        // Do something before request is sent
                        console.log("请求之前");
                        return config;
                    }, function (error) {
                        // Do something with request error
                        console.log("对错误deal");
                        return Promise.reject(error);
                    })  
                  const interTwn= axios.interceptors.response.use(function (response) {
                        // Do something with response data
                         axios.interceptors.request.eject(interOne);//取消一个拦截器
                         console.log("this is after");
                      return response;
                    }, function (error) {
                        // Do something with response error
                        return Promise.reject(error);
                    })
                }
            },
            mounted(){
                this.getList();
             }
    };    
    const myVue=new Vue({
        el:'#app',
        components:{
            myF1:c1,
        }   
    });

实际效果如下:(可以看到在一定的时间延迟之后会输出‘this is after’,并且也请求到了后端数据......)

 

 

 

 

 

转载于:https://www.cnblogs.com/evaling/p/7607603.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值