vue-resource HTTP API基础

来源:互联网 发布:中国城镇住户调查数据 编辑:程序博客网 时间:2024/06/08 05:05

vue-resource特点

vue-resource插件具有以下特点:

1. 体积小

vue-resource非常小巧,在压缩以后只有大约12KB,服务端启用gzip压缩后只有4.5KB大小,这远比jQuery的体积要小得多。

2. 支持主流的浏览器

和Vue.js一样,vue-resource除了不支持IE 9以下的浏览器,其他主流的浏览器都支持。

3. 支持Promise API和URI Templates

Promise是ES6的特性,Promise的中文含义为“先知”,Promise对象用于异步计算。
URI Templates表示URI模板,有些类似于ASP.NET MVC的路由模板。

4. 支持拦截器

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

vue-resource使用

引入vue-resource

<script src="js/vue.js"></script><script src="js/vue-resource.js"></script>

HTTP

The http service can be used globally Vue.http or in a Vue instancethis.$http.

Usage

A Vue instance provides the this.$http service which can send HTTP requests. A request method call returns aPromise that resolves to the response. Also the Vue instance will be automatically bound tothis in all function callbacks.

{  // GET /someUrl  this.$http.get('/someUrl').then(response => {    // success callback  }, response => {    // error callback  });}

Methods

Shortcut methods are available for all request types. These methods work globally or in a Vue instance.

// global Vue objectVue.http.get('/someUrl', [options]).then(successCallback, errorCallback);Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);// in a Vue instancethis.$http.get('/someUrl', [options]).then(successCallback, errorCallback);this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

List of shortcut methods:

  • 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

ParameterTypeDescriptionurlstringURL to which the request is sentbodyObject, FormData, stringData to be sent as the request bodyheadersObjectHeaders object to be sent as HTTP request headersparamsObjectParameters object to be sent as URL parametersmethodstringHTTP method (e.g. GET, POST, ...)responseTypestringType of the response body (e.g. text, blob, json, ...)timeoutnumberRequest timeout in milliseconds (0 means no timeout)beforefunction(request)Callback function to modify the request options before it is sentprogressfunction(event)Callback function to handle the ProgressEvent of uploadscredentialsbooleanIndicates whether or not cross-site Access-Control requests should be made using credentialsemulateHTTPbooleanSend PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override headeremulateJSONbooleanSend request body as application/x-www-form-urlencoded content type

Response

A request resolves to a response object with the following properties and methods:

PropertyTypeDescriptionurlstringResponse URL originbodyObject, Blob, stringResponse bodyheadersHeaderResponse Headers objectokbooleanHTTP status code between 200 and 299statusnumberHTTP status code of the responsestatusTextstringHTTP status text of the responseMethodTypeDescriptiontext()PromiseResolves the body as stringjson()PromiseResolves the body as parsed JSON objectblob()PromiseResolves the body as Blob object

Example

{  // POST /someUrl  this.$http.post('/someUrl', {foo: 'bar'}).then(response => {    // get status    response.status;    // get status text    response.statusText;    // get 'Expires' header    response.headers.get('Expires');    // get body data    this.someData = response.body;  }, response => {    // error callback  });}

Fetch an image and use the blob() method to extract the image body content from the response.

{  // GET /image.jpg  this.$http.get('/image.jpg').then(response => {    // resolve to Blob    return response.blob();  }).then(blob => {    // use image Blob  });}

Interceptors

Interceptors can be defined globally and are used for pre- and postprocessing of a request. If a request is send usingthis.$http or this.$resource the current Vue instance is available asthis in a interceptor callback.

Request processing

Vue.http.interceptors.push(function(request, next) {  // modify method  request.method = 'POST';  // modify headers  request.headers.set('X-CSRF-TOKEN', 'TOKEN');  request.headers.set('Authorization', 'Bearer TOKEN');  // continue to next interceptor  next();});

Request and Response processing

Vue.http.interceptors.push(function(request, next) {  // modify request  request.method = 'POST';  // continue to next interceptor  next(function(response) {    // modify response    response.body = '...';  });});

Return a Response and stop processing

Vue.http.interceptors.push(function(request, next) {  // modify request ...  // stop and return response  next(request.respondWith(body, {    status: 404,    statusText: 'Not found'  }));});

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 剩米饭反潮了怎么办 吃馊米饭中毒后怎么办? 蒸熟的米饭发黄怎么办 孕妇肉类吃的少怎么办 大米饭坏了吃了怎么办 米饭煮糊了锅怎么办 减肥吃了猪肉脯怎么办 吃了硬米饭胃痛怎么办 宝宝吃了硬物怎么办 米饭卡在喉咙里了怎么办 喉咙里卡了米饭怎么办 孕妇吃了坏鹅蛋怎么办 1岁大宝宝长短腿怎么办 行测中的判断推理怎么办 塑料盖子玻璃罐头瓶子打不开怎么办 猪肉烫火锅吃怎么办料 自制腊肠放干了怎么办 孕妇吃了4块腊肉怎么办 衣服沾了火锅味怎么办 皮包上有火锅味怎么办 芝士年糕裂开了怎么办 制作牛肉酱咸了怎么办 腌牛肉太咸了怎么办 八宝粥的拉环断了怎么办 八宝粥易拉罐拉环断了怎么办 吃完辣的胃难受怎么办 天天呆在家很烦怎么办 吃多了荔枝上火怎么办 猛犸牙牌子裂了怎么办 玩游戏电脑卡了怎么办 电脑打开卡在选项界面怎么办? 红警突然卡死怎么办 柯基不吃狗粮怎么办 貔貅嘴巴磕破了怎么办 开光貔貅牙磕了怎么办 玉貔貅鼻子碎了怎么办 开光的貔貅摔坏了怎么办 貔貅摔坏了耳朵怎么办? 貔貅摔坏了一点点怎么办 天猫删评价扣4分怎么办 暴风影音下载电视剧下载不了怎么办