vue-resouce

作者: 寒梁沐月 | 来源:发表于2017-04-03 12:40 被阅读355次

vue-resource特点:

  1. 体积小
    vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。
  1. 支持主流的浏览器
    和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。
  2. 支持Promise API和URI Templates
    Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。
    URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。
  3. 支持拦截器
    拦截器是全局的,拦截器可以在请求发送前和发送请求后做一些处理。
    拦截器在一些场景下会非常有用,比如请求发送前在headers中设置access_token,或者在请求失败时,提供共通的处理方式。

基本语法

引入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方法有两个参数,第一个参数是响应成功时的回调函数,第二个参数是响应失败时的回调函数。

then方法的回调函数也有两种写法,第一种是传统的函数写法,第二种是更为简洁的ES 6的Lambda写法:

// 传统写法
this.$http.get('/someUrl', [options]).then(function(response){
    // 响应成功回调
}, function(response){
    // 响应错误回调
});


// Lambda写法
this.$http.get('/someUrl', [options]).then((response) => {
    // 响应成功回调
}, (response) => {
    // 响应错误回调
});

vue-resource的请求API是按照REST风格设计的,它提供了7种请求API:

get(url, [options])
head(url, [options])
delete(url, [options])
jsonp(url, [options])
post(url, [body], [options])
put(url, [body], [options])
patch(url, [body], [options])

options对象
发送请求时的options选项对象包含以下属性:

参数 类型 描述
url string 请求的URL
method string 请求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法
body Object,FormDatastring request body
params Object 请求的URL参数对象
headers Object request header
timeout number 单位为毫秒的请求超时时间 (0 表示无超时时间)
before function(request) 请求发送前的处理函数,类似于jQuery的beforeSend函数
progress function(event) ProgressEvent回调处理函数
credientials boolean 表示跨域请求时是否需要使用凭证
emulateHTTP boolean 发送PUT, PATCH, DELETE请求时以HTTP POST的方式发送,并设置请求头的X-HTTP-Method-Override
emulateJSON boolean 将request body以application/x-www-form-urlencoded content type发送

emulateHTTP的作用

如果Web服务器无法处理PUT, PATCH和DELETE这种REST风格的请求,你可以启用enulateHTTP现象。启用该选项后,请求会以普通的POST方法发出,并且HTTP头信息的X-HTTP-Method-Override属性会设置为实际的HTTP方法。

Vue.http.options.emulateHTTP = true;

emulateJSON的作用

如果Web服务器无法处理编码为application/json的请求,你可以启用emulateJSON选项。启用该选项后,请求会以application/x-www-form-urlencoded作为MIME type,就像普通的HTML表单一样。

Vue.http.options.emulateJSON = true;

response对象

response对象包含以下属性:

方法 类型 描述
text() string 以string形式返回response body
json() Object 以JSON对象形式返回response body
blob() Blob 以二进制形式返回response body
属性 类型 描述
ok boolean 响应的HTTP状态码在200~299之间时,该属性为true
status number 响应的HTTP状态码
statusText string 响应的状态文本
headers Object 响应头
代码示例
1.get
vm.$http.get(this.apiUrl)
    .then((response) => {
            this.$set('gridData', response.data)
    })
    .catch(function(response) {
            console.log(response)
    })
2.post
vm.$http.post(vm.apiUrl, {},{emulateJSON:true})
    .then((response) => {

    })
3.delect
vm.$http.delete(this.apiUrl )
    .then((response) => {
            
    })
4.put
vm.$http.put(this.apiUrl)
    .then((response) => {
                
    })
5.jsonp
    vm.$http.jsonp(this.apiUrl)
              .then(function(response){
    
    })

使用resource服务

vue-resource提供了另外一种方式访问HTTP——resource服务,resource服务包含以下几种默认的action:

get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}

resource对象也有两种访问方式:

全局访问:Vue.resource
实例访问:this.$resource

resource可以结合URI Template一起使用,以下示例的apiUrl都设置为{/id}了:
apiUrl: 'http://211.149.193.19:8080/api/customers{/id}'
GET请求
使用get方法发送GET请求,下面这个请求没有指定{/id}

getCustomers: function() {

    var resource = this.$resource(this.apiUrl)
        vm = this

    resource.get()
        .then((response) => {
            vm.$set('gridData', response.data)
        })
        .catch(function(response) {
            console.log(response)
        })
}

POST请求
使用save方法发送POST请求,下面这个请求没有指定{/id}

createCustomer: function() {
    var resource = this.$resource(this.apiUrl)
        vm = this

    resource.save(vm.apiUrl, vm.item)
        .then((response) => {
            vm.$set('item', {})
            vm.getCustomers()
        })
    this.show = false
}

PUT请求
使用update方法发送PUT请求,下面这个请求指定了{/id}

updateCustomer: function() {
    var resource = this.$resource(this.apiUrl)
        vm = this

    resource.update({ id: vm.item.customerId}, vm.item)
        .then((response) => {
            vm.getCustomers()
        })
}

DELETE请求
使用remove或delete方法发送DELETE请求,下面这个请求指定了{/id}

deleteCustomer: function(customer){
    var resource = this.$resource(this.apiUrl)
        vm = this

    resource.remove({ id: customer.customerId})
        .then((response) => {
            vm.getCustomers()
        })
}

拦截器

在vue项目使用vue-resource的过程中,临时增加了一个需求,需要在任何一个页面任何一次http请求,增加对token过期的判断,如果token已过期,需要跳转至登录页面。如果要在每个页面中的http请求操作中添加一次判断,那么会是一个非常大的修改工作量。那么vue-resource是否存在一个对于任何一次请求响应捕获的的公共回调函数呢?答案是有的!

vue-resource的interceptors拦截器的作用正是解决此需求的妙方。在每次http的请求响应之后,如果设置了拦截器如下,会优先执行拦截器函数,获取响应体,然后才会决定是否把response返回给
then进行接收。那么我们可以在这个拦截器里边添加对响应状态码的判断,来决定是跳转到登录页面还是留在当前页面继续获取数据。

下边代码添加在main.js中
Vue.http.interceptors.push((request, next) => {
 console.log(this)//此处this为请求所在页面的Vue实例
  // modify request
  request.method = 'POST';//在请求之前可以进行一些预处理和配置

  // continue to next interceptor
  next((response) => {//在响应之后传给then之前对response进行修改和逻辑判断。对于token时候已过期的判断,就添加在此处,页面中任何一次http请求都会先调用此处方法

      response.body = '...';
    return response;

  });
});

相关文章

网友评论

    本文标题:vue-resouce

    本文链接:https://www.haomeiwen.com/subject/stonottx.html