异步查询数据,自然是通过 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>

 

原文地址:http://www.cnblogs.com/sfwu/p/16908184.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性