vue-resource Build Downloads jsdelivr Version License

The plugin for Vue.js provides services for making web requests and handle responses using a XMLHttpRequest or JSONP.Vue.js插件提供了使用XMLHttpRequest或JSONP发出web请求和处理响应的服务。

Features功能

Installation安装

You can install it via yarn or NPM.您可以通过yarnNPM进行安装。

$ yarn add vue-resource
$ npm install vue-resource

CDN

Available on jsdelivr, unpkg or cdnjs.可以在jsdelivrunpkgcdnjs上找到。

<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.3"></script>

Example示例

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

    // get body data
    this.someData = response.body;

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

Documentation文档

Changelog变更日志

Details changes for each release are documented in the release notes.每个版本的详细更改记录在发行说明中。

Contribution贡献

If you find a bug or want to contribute to the code or documentation, you can help by submitting an issue or a pull request.如果您发现一个bug或希望对代码或文档做出贡献,您可以通过提交问题发起请求来提供帮助。

License许可证

MIT


Configuration配置

Set default values using the global configuration.使用全局配置设置默认值。

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

Set default values inside your Vue component options.在Vue组件选项中设置默认值。

new Vue({

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

})

Note that for the root option to work, the path of the request must be relative. 请注意,要使root选项起作用,请求的路径必须是相对的。This will use this the root option: Vue.http.get('someUrl') while this will not: Vue.http.get('/someUrl').这将使用这个根选项:Vue.http.get('someUrl'),而不是:Vue.http.get('/someUrl')

Webpack/Browserify

Add vue and vue-resource to your package.json, then npm install, then add these lines in your code:vuevue-resource添加到package.json中,然后npm install,然后在代码中添加以下行:

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

Vue.use(VueResource);

Legacy web servers遗留web服务器

If your web server can't handle requests encoded as application/json, you can enable the emulateJSON option. 如果您的web服务器无法处理编码为application/json的请求,则可以启用emulateJSON选项。This will send the request as application/x-www-form-urlencoded MIME type, as if from an normal HTML form.这将以application/x-www-form-urlencodedMIME类型发送请求,就像从普通HTML表单发送一样。

Vue.http.options.emulateJSON = true;

If your web server can't handle REST/HTTP requests like PUT, PATCH and DELETE, you can enable the emulateHTTP option. 如果您的web服务器无法处理REST/HTTP请求,如PUTPATCHDELETE,则可以启用emulateHTTP选项。This will set the X-HTTP-Method-Override header with the actual HTTP method and use a normal POST request.这将使用实际的HTTP方法设置X-HTTP-Method-Override头,并使用正常的POST请求。

Vue.http.options.emulateHTTP = true;

Typescript Support支持

Typescript for vue-resource should work out of the box since the type definition files are included within the npm package.vue资源的Typescript应该是现成的,因为类型定义文件包含在npm包中。


HTTP

The http service can be used globally Vue.http or in a Vue instance this.$http.http服务可以全局使用Vue.http,也可以在Vue实例this.$http中使用。

Usage

A Vue instance provides the this.$http service which can send HTTP requests. Vue实例提供this.$http服务,该服务可以发送http请求。A request method call returns a Promise that resolves to the response. 请求方法调用返回解析为响应的PromiseAlso the Vue instance will be automatically bound to this in all function callbacks.此外,Vue实例将在所有函数回调中自动绑定到this

{
  // 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.快捷方式方法可用于所有请求类型。这些方法在全局范围内或在Vue实例中工作。

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

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

List of shortcut methods:快捷方式列表:

Config配置

Parameter参数 Type类型 Description描述
url string URL to which the request is sent请求发送到的URL
body Object, FormData, string Data to be sent as the request body作为请求主体发送的数据
headers Object Headers object to be sent as HTTP request headers要作为HTTP请求头发送的Headers对象
params Object Parameters object to be sent as URL parameters要作为URL参数发送的参数对象
method string HTTP method (e.g. GET, POST, ...)HTTP方法(例如GETPOST等)
responseType string Type of the response body (e.g. text, blob, json, ...)响应主体的类型(例如文本、blob、json等)
timeout number Request timeout in milliseconds (0 means no timeout)请求超时(毫秒)(0表示无超时)
credentials boolean Indicates whether or not cross-site Access-Control requests should be made using credentials指示是否应使用凭据发出跨站点访问控制请求
emulateHTTP boolean Send PUT, PATCH and DELETE requests with a HTTP POST and set the X-HTTP-Method-Override header使用HTTP POST发送PUTPATCH和DELETE请求,并设置X-HTTP-Method-Override标头
emulateJSON boolean Send request body as application/x-www-form-urlencoded content type将请求正文以application/x-www-form-urlencoded内容类型的形式发送
before function(request) Callback function to modify the request object before it is sent回调函数,用于在发送请求对象之前对其进行修改
uploadProgress function(event) Callback function to handle the ProgressEvent of uploads用于处理上载的ProgressEvent的回调函数
downloadProgress function(event) Callback function to handle the ProgressEvent of downloads用于处理下载的ProgressEvent的回调函数

Response

A request resolves to a response object with the following properties and methods:请求解析为具有以下属性和方法的响应对象:

Property属性 Type类型 Description描述
url string Response URL origin响应URL源
body Object, Blob, string Response body响应体
headers Header Response Headers object响应头对象
ok boolean HTTP status code between 200 and 299HTTP状态代码介于200和299之间
status number HTTP status code of the response响应的HTTP状态代码
statusText string HTTP status text of the response响应的HTTP状态文本
Method方法 Type类型 Description描述
text() Promise Resolves the body as string将主体解析为字符串
json() Promise Resolves the body as parsed JSON object将主体解析为已解析的JSON对象
blob() Promise Resolves the body as Blob object将实体解析为Blob对象

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
  });
}

Send a get request with URL query parameters and a custom headers.发送带有URL查询参数和自定义标题的get请求。

{
  // GET /someUrl?foo=bar
  this.$http.get('/someUrl', {params: {foo: 'bar'}, headers: {'X-Custom': '...'}}).then(response => {
    // success callback
  }, response => {
    // error callback
  });
}

Fetch an image and use the blob() method to extract the image body content from the response.获取图像并使用blob()方法从响应中提取图像正文内容。

{
  // GET /image.jpg
  this.$http.get('/image.jpg', {responseType: 'blob'}).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 sent using this.$http or this.$resource the current Vue instance is available as this in a interceptor callback.如果使用this.$httpthis.$resource发送请求,则当前Vue实例在拦截器回调中可用。

Request processing请求处理

Vue.http.interceptors.push(function(request) {

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

  // modify headers
  request.headers.set('X-CSRF-TOKEN', 'TOKEN');
  request.headers.set('Authorization', 'Bearer TOKEN');

});

Request and Response processing请求和响应处理

Vue.http.interceptors.push(function(request) {

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

  // return response callback
  return function(response) {

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

  };
});

Return a Response and stop processing返回响应并停止处理

Vue.http.interceptors.push(function(request) {

  // modify request修改请求 ...

  // stop and return respons停止并返回响应e
  return request.respondWith(body, {
    status: 404,
    statusText: 'Not found'
  });
});

Overriding default interceptors覆盖默认拦截器

All default interceptors callbacks can be overriden to change their behavior. 可以覆盖所有默认侦听器回调以更改其行为。All interceptors are exposed through the Vue.http.interceptor object with their names before, method, jsonp, json, form, header and cors.所有拦截器都是通过Vue.http.interceptor对象公开的,使用它们的名称beforemethodjsonpjsonformheadercors

Vue.http.interceptor.before = function(request) {

  // override before interceptor拦截器前覆盖

};

Resource资源

The resource service can be used globally Vue.resource or in a Vue instance this.$resource.资源服务可以全局使用Vue.resource,也可以在Vue实例中使用 this.$resource

Methods方法

Default Actions默认操作

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

Example示例

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

  // GET someItem/1
  resource.get({id: 1}).then(response => {
    this.item = response.body;
  });

  // 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
  });
}

Custom Actions自定义操作

{
  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.item = response.body;
  });

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

Note: When passing only one single object (for POST, PUT and PATCH custom actions), it will defaults to body param. 当只传递一个对象时(对于POST、PUT和PATCH自定义操作),它将默认为body参数。If you need set url params you will have to pass an empty object as second argument.如果需要设置url参数,则必须传递一个空对象作为第二个参数。

{
  var resource = this.$resource('someItem{/id}', {}, {
    baz: {method: 'POST', url: 'someItem/baz{/id}'}
  });

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

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

Code Recipes代码案例

The Recipes provide code examples to common use-cases. 这些配方提供了常见用例的代码案例。If you want to share your recipe feel free to send a pull request.如果你想分享你的案例,请随时发送拉请求

Forms表单

Sending forms using FormData.使用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
  });
}

Abort a request中止请求

Abort a previous request when a new request is about to be sent. 将要发送新请求时中止以前的请求。For example when typing in a autocomplete input.例如,在键入自动完成输入时。

{
  // 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在Vue实例上设置上一个请求
      this.previousRequest = request;
    }

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

API ReferenceAPI参考

Request

{
  // Constructor
  constructor(object: config)

  // Properties
  url (string)
  body (any)
  headers (Headers)
  method (string)
  params (object)
  timeout (number)
  credentials (boolean)
  emulateHTTP (boolean)
  emulateJSON (boolean)
  before (function(Request))
  progress (function(Event))

  // Methods
  getUrl() (string)
  getBody() (any)
  respondWith(any: body, object: config) (Response)
  abort()
}

Response

{
  // Constructor
  constructor(any: body, object: {string: url, object: headers, number: status, string: statusText})

  // Properties
  url (string)
  body (any)
  headers (Headers)
  ok (boolean)
  status (number)
  statusText (string)

  // Methods
  blob() (Promise)
  text() (Promise)
  json() (Promise)
}

Headers

{
  // Constructor
  constructor(object: headers)

  // Properties
  map (object)

  // Methods
  has(string: name) (boolean)
  get(string: name) (string)
  getAll() (string[])
  set(string: name, string: value) (void)
  append(string: name, string: value) (void)
  delete(string: name) (void)
  forEach(function: callback, any: thisArg) (void)
}