首页 > 其他分享 >异步查询工具 axios

异步查询工具 axios

时间:2022-11-20 15:59:12浏览次数:43  
标签:异步 axios console 请求 查询 Vue data log

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

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,console,请求,查询,Vue,data,log
From: https://www.cnblogs.com/sfwu/p/16908184.html

相关文章

  • Django ORM 多表操作:一对一、一对多、多对多的增删改,基于对象/双下划线的跨表查询
    DjangomodelORM数据表相关操作分析思路,创建数据表对于表操作,表之间的关联关系,必须理解他们之间的关系,对于编程很重要。可以看看映射关系、外键和relationship查询,至少明......
  • Laravel:whereIn子查询
    文档​​https://learnku.com/docs/laravel/9.x/queries/12246#08034f​​示例如下$users=User::whereNotIn('id',function($query)use($user){$query->se......
  • 多表查询,子查询
    分页查询按雇员的id号升序取出,每页显示3条记录,请分别显示第一页,第二页,第三页基本语法:select....limitstart,rows表示从start+1开始取,取出rows行,start从0开始计算公......
  • 数据库无法查询中文问题的解决过程
    解决方案:在数据库连接后面指定编码&useUnicode=true&characterEncoding=UTF-8比如url:jdbc:mysql://localhost:3306/store_category?useSSL=false&?useUnicode=true&ch......
  • MacBook苹果笔记本电脑 如何查询CPU GPU 温度?
     苹果笔记本电脑高负荷下发热量巨大,为了散热买了个散热器,于是乎,如何观察散热效果?方法如下:1、打开苹果内置终端,输入命令:sudopowermetrics--samplerssmc|grept......
  • Axios异步框架
    1、Axios对原生的AJAX进行封装,简化书写。 2、官网:https://www.axios-http.cn 3、axios的使用   4、 ......
  • 北京公交卡余额查询
    北京公交卡余额查询输入卡号,立即查询出这个卡最近坐车情况(上车,下车),余额,充值等信息,非常方便的了解这个卡的情况。目前针对android2.1及以上版本......
  • Hive学习笔记:with as子查询
    一、说明与其他SQL语法类似,Hive中也支持withas将一大段SQL语句封装为子查询,方便后续多次调用。MySQL旧版本不支持withas语法,8.0才支持。withttas( selec......
  • java常用查询
     生成文档javadoc-ddoc hello.java                   ......
  • MySQL查询技巧
    查询字符串截取最后一个指定字符前面的字符串用途:可以用于截取最后一个逗号前面的字符串,就是去掉最后一个逗号后面的字符串--查询原字符串,截取原字符串从第1位开始到......