vue-resource

– 配置
使用全局配置设置默认值

Vue.http.options.root = '/root';
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';

在你的Vue组件配置中设置默认值

new Vue({

  http: {
    root: '/root',
    headers: {
      Authorization: 'Basic YXBpOnBhc3N3b3Jk'
    }
  }

})

Webpack/Browserify(两种前端打包/构建工具)

在你项目中的package.json文件中添加vue和vue-resource依赖,然后在命令行中执行npm install,然后将如下代码拷贝到你的项目入口文件中。

var Vue = require('vue');
var VueResource = require('vue-resource');

Vue.use(VueResource);

传统WEB服务器

如果你的WEB服务器不能处理编码为application/json的请求,你可以将emulateJSON选项配置为enable。然后Vue-resource会将发送的请求MIME类型设为application/x-www-form-urlencoded,就像一个标准的HTML表单提交的MIME类型一样。

Vue.http.options.emulateJSON = true;

如果你的WEB服务器不能处理类似于PUT,PATCH和DELETE这种REST/HTTP请求,你可以将emulateHTTP选项配置为enable。这样将会通过设置HTTP Header(头部)为X-HTTP-Method-Override的方式携带上原始的HTTP请求方法,并且通过标准的POST方法发送请求。

Vue.http.options.emulateHTTP = true;

HTTP

你可以使用全局对象方式Vue.http或者在一个Vue实例的内部使用this.$http来发起HTTP请求。

语法

一个Vue实例内部提供的this.$http服务可以发送HTTP请求。一个请求方法的回调请参考 Promise它可以解决这些响应。当然Vue实例将自动绑定到this在所有的函数回调中。

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

方法

我们为所有的请求类型提供了一套简便的方法。 这些方法可以在全局或一个Vue实例中工作。

// global Vue object
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);

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

简便方法的列表:

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

选项

参数	类型	描述
url	string	请求的目标URL
body	Object, FormData, string	作为请求体发送的数据
headers	Object	作为请求头部发送的头部对象
params	Object	作为URL参数的参数对象
method	string	HTTP方法 (例如GET,POST,...)
timeout	number	请求超时(单位:毫秒) (0表示永不超时)
before	function(request)	在请求发送之前修改请求的回调函数
progress	function(event)	用于处理上传进度的回调函数 ProgressEvent
credentials	boolean	是否需要出示用于跨站点请求的凭据
emulateHTTP	boolean	是否需要通过设置X-HTTP-Method-Override头部并且以传统POST方式发送PUT,PATCH和DELETE请求。
emulateJSON	boolean	设置请求体的类型为application/x-www-form-urlencoded

响应

通过如下属性和方法处理一个请求获取到的响应对象:

属性	类型	描述
url	string	响应的URL源
body	Object, Blob, string	响应体数据
headers	Header	请求头部对象
ok	boolean	当HTTP响应码为200到299之间的数值时该值为true
status	number	HTTP响应吗
statusText	string	HTTP响应状态
方法	类型	描述
text()	约定值	以字符串方式返回响应体
json()	约定值	以格式化后的json对象方式返回响应体
blob()	约定值	以二进制Blob对象方式返回响应体

例子

{
  // 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');

    // set data on vm
    this.$set('someData', response.body);

  }, (response) => {
    // error callback
  });
}

使用blob()方法从响应中获取一副图像的内容。

{
  // GET /image.jpg
  this.$http.get('/image.jpg').then((response) => {

    // resolve to Blob
    return response.blob();

  }).then(blob) => {
    // use image Blob
  });
}

拦截器

全局定义拦截器后,它可用于前置和后置处理请求。
请求处理

Vue.http.interceptors.push((request, next) => {

  // modify request
  request.method = 'POST';

  // continue to next interceptor
  next();
});

请求与响应处理

Vue.http.interceptors.push((request, next)  => {

  // modify request
  request.method = 'POST';

  // continue to next interceptor
  next((response) => {

    // modify response
    response.body = '...';

  });
});

返回一个响应并且停止处理

Vue.http.interceptors.push((request, next) => {

  // modify request ...

  // stop and return response
  next(request.respondWith(body, {
    status: 404,
    statusText: 'Not found'
  }));
});

资源

你可以使用全局的Vue.resource或者在一个Vue实例内部使用this.$resource发起一个Resource请求。

方法

resource(url, [params], [actions], [options])

默认操作

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

例子

{
  var resource = this.$resource('someItem{/id}');

  // GET someItem/1
  resource.get({id: 1}).then((response) => {
    this.$set('item', response.json())
  });

  // POST someItem/1
  resource.save({id: 1}, {item: this.item}).then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });

  // DELETE someItem/1
  resource.delete({id: 1}).then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}

自定义操作

{
  var customActions = {
    foo: {method: 'GET', url: 'someItem/foo{/id}'},
    bar: {method: 'POST', url: 'someItem/bar{/id}'}
  }

  var resource = this.$resource('someItem{/id}', {}, customActions);

  // GET someItem/foo/1
  resource.foo({id: 1}).then((response) => {
    this.$set('item', response.json())
  });

  // POST someItem/bar/1
  resource.bar({id: 1}, {item: this.item}).then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}

编码规范

这里提供了一套通用的编码规范。如果你想分享你的较为自由的编码规范,可以发起pull request.
表单

使用FormData发送表单。

{
  var formData = new FormData();

  // append string
  formData.append('foo', 'bar');

  // append Blob/File object
  formData.append('pic', fileInput, 'mypic.jpg');

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

终止请求

当一个新的请求被发送的时候请终止上一个请求。例如在一个自动完成的输入框中输入的时候。

{
  // GET /someUrl
  this.$http.get('/someUrl', {

    // use before callback
    before(request) {

      // abort previous request, if exists
      if (this.previousRequest) {
        this.previousRequest.abort();
      }

      // set previous request on Vue instance
      this.previousRequest = request;
    }

  }).then((response) => {
    // success callback
  }, (response) => {
    // error callback
  });
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值