异步查询工具 axios

  异步查询数据,自然是通过 ajax 查询,大家首先想起的肯定是jQuery。但 jQuery 与 MVVM 的思想不吻合,而且 ajax 只是 jQuery 的一小部分。因此不可能为了发起 ajax 请求而去引用这么大的一个库。所以 Vue 官方推荐的 ajax 请求框架叫做:axios。

  axios 处理请求的原则会根据请求数据的格式来定:

  1、如果是请求对象:会转为 JSON 发送。

  2、如果请求是 String:会作为普通表单请求发送,但需要保证 String 格式是键值对。

axios 的 Get 请求语法:

axios.get("/xxx/xxx/list?id=0") // 请求路径和请求参数拼接
    .then(function(resp){
        // 成功回调函数
    })
    .catch(function(){
        // 失败回调函数
    })
// 参数较多时,可以通过params来传递参数
axios.get("/xxx/xxx/list", {
        params:{
            id:0
        }
    })
    .then(function(resp){})// 成功时的回调
    .catch(function(error){})// 失败时的回调

axios 的 Post 请求语法:

比如新增一个用户

axios.post("/user",{
        name:"Jack",
        age:21
    })
    .then(function(resp){})
    .catch(function(error){})

  注意,POST请求传参,不需要像GET请求那样定义一个对象,在对象的params参数中传参。post()方法的第二个参数对象,就是将来要传递的参数,PUT 和 DELETE 请求与  POST 请求类似。

一、axios 异步查询的简单案例。

1、进入安装目录,通过命令下载 axios 。npm init --yes、npm install axios --save

2、引入 axios 模块。

<script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>

 3、将 axios 挂载到 Vue 对象上。

// 将axios挂载到Vue对象上
Vue.prototype.$axios = axios;

4、调用事件发送请求。

var App = {
  template:` 
    <div>
      <button @click='sendAjax'>发请求</button>
    </div>
   `,
  methods:{
    sendAjax(){
      this.$axios.get('http://127.0.0.1:8888')
      .then(res=>{
        console.log(res);
      })
      .catch(err=>{
        console.log(err);
      })
    }
}

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="app">
    </div>
    <script type="text/javascript" src="../vue/vue.js"></script>
    <script type="text/javascript" src="node_modules/axios/dist/axios.js"></script>
    <script type="text/javascript">
        var App = {
            template:` 
                <div>
                    <button @click='sendAjax'>发请求</button>
                </div>
            `,
            methods:{
                sendAjax(){
                    this.$axios.get('http://127.0.0.1:8888')
                    .then(res=>{
                        console.log(res);
                    })
                    .catch(err=>{
                        console.log(err);
                    })
                }
            }
        }
        // 将axios挂载到Vue对象上
        Vue.prototype.$axios = axios
        new Vue({
            el:'#app',
            template:` 
                <App/>
            `,
            components:{
                App
            }
        });
    </script>
</body>
</html>

二、合并请求,顾名思义就是将多个请求合并在一起,使用 axios 中的 all 方法实现。

1、定义多个请求。

// 并发请求
// 请求1 get:/
// 请求2 post:/add
var q1 = this.$axios.get('http://127.0.0.1:8888/');
var q2 = this.$axios.post('http://127.0.0.1:8888/add','a=1');

2、调用 axios 对象的 all([参数1 , 参数2]) 方法,将请求合并在一起。

this.$axios.all([q1,q2])
.then(this.$axios.spread((res1,res2)=>{
// 全部成功了
this.res1 = res1.data;
this.res2 = res2.data;
}))
.catch(err=>{ // 其一失败 console.log(err); })

代码如下:

    <script type="text/javascript">
        var App = {
            data(){
                return{
                    res1:'',
                    res2:''
                }
            },
            template:` 
                <div>
                    响应1:{{res1}}
                    响应2:{{res2}}
                    <button @click='sendAjax'>
                        合并请求
                    </button>
                </div>
            `,
            methods:{
                sendAjax(){
                    // 并发请求
                    // 请求1 get:/
                    // 请求2 post:/add
                    var q1 = this.$axios.get('http://127.0.0.1:8888/');
                    var q2 = this.$axios.post('http://127.0.0.1:8888/add','a=1');
                    this.$axios.all([q1,q2])
                    .then(this.$axios.spread((res1,res2)=>{
                        // 全部成功了
                        this.res1 = res1.data;
                        this.res2 = res2.data;
                    }))
                    .catch(err=>{
                        // 其一失败
                        console.log(err);
                    })
                }
            }
        }
        // 将axios挂载到Vue对象上
        Vue.prototype.$axios = axios
        new Vue({
            el:'#app',
            template:` 
                <App/>
            `,
            components:{
                App
            }
        });
    </script>

三、axios 中的请求配置 options。

1、 配置默认的基础路径:

this.$axios.defaults.baseURL='http://127.0.0.1:8888/';

2、配置查询字符串或对象。

params:{
    id:0
}
或
{
    name:"Jack",
    age:21
}

3、转换请求体数据。

 

  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
  // 你可以修改请求头。
  transformRequest: [function (data, headers) {
    // 对发送的 data 进行任意转换处理

    return data;
  }],

4、转换响应体数据。

 

  // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
  transformResponse: [function (data) {
    // 对接收的 data 进行任意转换处理

    return data;
  }],

5、header 头信息。

  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},

6、data 请求数据。

  // `data` 是作为请求体被发送的数据
  // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
  // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属: FormData, File, Blob
  // - Node 专属: Stream, Buffer
  data: {
    firstName: 'Fred'
  },

7、设置请求响应时间(毫秒)。

  // `timeout` 指定请求超时的毫秒数。
  // 如果请求时间超过 `timeout` 的值,则请求会被中断
  timeout: 1000, // 默认值是 `0` (永不超时)

 代码如下:

    <script type="text/javascript">
        var App = {
            template:` 
                <div>
                    <button @click='sendAjax'>发请求</button>
                </div>
            `,
            methods:{
                sendAjax(){
                    this.$axios.defaults.baseURL = 'http://127.0.0.1:8888/'
                    this.$axios.get('', {
                        params:{id:1},
                        // 在传递给then/catch之前,允许修改响应的数据
                        transformResponse: [function 
                            (data){
                            // 对data进行任意转换处理
                            console.log(data);
                            console.log(typeof data);

                            data = JSON.parse(data);
                            console.log(data);

                            return data;
                        }],
                    })
                    .then(res=>{
                        console.log(res.data.msg);
                    })
                    .catch(err=>{
                        console.log(err)
                    })

                    this.$axios.post('/add',{
                        firstName: 'Fred'
                      },
                      {
                         // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
                          transformRequest: [function (data) {
                            // 对接收的 data 进行任意转换处理
                            console.log(data);
                            return data;
                          }],
                    })
                    .then(res=>{
                        console.log(res);
                    })
                    .catch(err=>{
                        console.log(err);
                    })
                }
            }
        }
        // 将axios挂载到Vue对象上
        Vue.prototype.$axios = axios
        new Vue({
            el:'#app',
            template:` 
                <App/>
            `,
            components:{
                App
            }
        });
    </script>

 注意:axios处理请求体的原则会根据请求数据的格式来定:

  • 如果请求体是对象:会转为json发送

  • 如果请求体是String:会作为普通表单请求发送,但需要保证String的格式是键值对。

    如:name=jack&age=12

当需要接收的参数 String 的格式是键值对时,可通过 QS(Query String,请求参数字符串)工具转换。

1、可通过 npm install qs --save 安装 QS 工具。

2、使用QS 工具中的 stringify 方法,可便捷实现 JS 中的 Object 与 QueryString 的转换。

const arr = [{name:"战三",age:24}];
console.log(this.$qs.stringify(arr));

至此,参数转换完成后,就可以使用了。

 

posted @ 2022-11-20 15:43  炒股沦为首负  阅读(71)  评论(0编辑  收藏  举报