vue-resource

vue-resource插件为vue.js提供发起网络请求的服务,使用XMLHttpRequest或JSONP处理服务端的响应。

一,安装

1)npm install vue-resource

2)import Vue from 'vue'

  import VueResource from 'vue-resource'

  Vue.use(VueResource)

也可以使用全局的 script 标签引入该插件

二,基本用法

 引入vue-resource后,可以基于全局的Vue对象使用http,也可以基于某个Vue实例使用http

// 基于全局Vue对象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

// 在一个Vue实例内使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

在发送请求后,使用then方法来处理响应结果,then方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数
this.$http.post(require("xxx.do", postData)
.then(res => {
    ...
    return this.$http.post("xxx.do")
})
.then(res => {
    this.$store.commit("setWxUserInfo", res.body);    
})

三,支持拦截器

拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。

 通过inteceptor,我们可以为所有的请求处理加一个loading:请求发送前显示loading,接收响应后隐藏loading。

Vue.http.interceptors.push(function (request, next) {
    //请求前显示加载中弹框
    next(function (response) {
        if (response.body.ReturnCode != "000000") {
            //提示错误信息response.body.ReturnMsg
        }
        //隐藏加载中弹框
        return response; 
    })
})
原文地址:https://www.cnblogs.com/colorful-coco/p/8022705.html