The plugin for Vue.js provides services for making web requests and handle responses using a XMLHttpRequest or JSONP.Vue.js插件提供了使用XMLHttpRequest或JSONP发出web请求和处理响应的服务。
You can install it via yarn or NPM.您可以通过yarn或NPM进行安装。
$ yarn add vue-resource
$ npm install vue-resource
Available on jsdelivr, unpkg or cdnjs.可以在jsdelivr、unpkg和cdnjs上找到。
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.5.3"></script>
{
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// get body data
this.someData = response.body;
}, response => {
// error callback
});
}
Details changes for each release are documented in the release notes.每个版本的详细更改记录在发行说明中。
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或希望对代码或文档做出贡献,您可以通过提交问题或发起请求来提供帮助。
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')
。
Add 将vue
and vue-resource
to your package.json
, then npm install
, then add these lines in your code:vue
和vue-resource
添加到package.json
中,然后npm install
,然后在代码中添加以下行:
var Vue = require('vue');
var VueResource = require('vue-resource');
Vue.use(VueResource);
If your web server can't handle requests encoded as 如果您的web服务器无法处理编码为application/json
, you can enable the emulateJSON
option. 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-urlencoded
MIME类型发送请求,就像从普通HTML表单发送一样。
Vue.http.options.emulateJSON = true;
If your web server can't handle REST/HTTP requests like 如果您的web服务器无法处理REST/HTTP请求,如PUT
, PATCH
and DELETE
, you can enable the emulateHTTP
option. PUT
、PATCH
和DELETE
,则可以启用emulateHTTP
选项。This will set the 这将使用实际的HTTP方法设置X-HTTP-Method-Override
header with the actual HTTP method and use a normal POST
request.X-HTTP-Method-Override
头,并使用正常的POST
请求。
Vue.http.options.emulateHTTP = true;
Typescript for vue-resource should work out of the box since the type definition files are included within the npm package.vue资源的Typescript应该是现成的,因为类型定义文件包含在npm包中。
The http service can be used globally http服务可以全局使用Vue.http
or in a Vue instance this.$http
.Vue.http
,也可以在Vue实例this.$http
中使用。
A Vue instance provides the Vue实例提供this.$http
service which can send HTTP requests. this.$http
服务,该服务可以发送http请求。A request method call returns a Promise that resolves to the response. 请求方法调用返回解析为响应的Promise。Also the Vue instance will be automatically bound to 此外,Vue实例将在所有函数回调中自动绑定到this
in all function callbacks.this
。
{
// GET /someUrl
this.$http.get('/someUrl').then(response => {
// success callback
}, response => {
// error callback
});
}
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:快捷方式列表:
get(url, [config])
head(url, [config])
delete(url, [config])
jsonp(url, [config])
post(url, [body], [config])
put(url, [body], [config])
patch(url, [body], [config])
url | string |
|
body | Object , FormData , string |
|
headers | Object |
|
params | Object |
|
method | string |
GET 、POST 等) |
responseType | string |
|
timeout | number |
0 means no timeout)0 表示无超时) |
credentials | boolean |
|
emulateHTTP | boolean |
X-HTTP-Method-Override headerPOST 发送PUT 、PATCH 和DELETE请求,并设置X-HTTP-Method-Override 标头 |
emulateJSON | boolean |
application/x-www-form-urlencoded content typeapplication/x-www-form-urlencoded 内容类型的形式发送 |
before | function(request) |
|
uploadProgress | function(event) |
ProgressEvent 的回调函数 |
downloadProgress | function(event) |
ProgressEvent 的回调函数 |
A request resolves to a response object with the following properties and methods:请求解析为具有以下属性和方法的响应对象:
url | string |
|
body | Object , Blob , string |
|
headers | Header |
|
ok | boolean |
|
status | number |
|
statusText | string |
text() | Promise |
|
json() | Promise |
|
blob() | Promise |
{
// 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 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.$http
或this.$resource
发送请求,则当前Vue实例在拦截器回调中可用。
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');
});
Vue.http.interceptors.push(function(request) {
// modify request
request.method = 'POST';
// return response callback
return function(response) {
// modify response
response.body = '...';
};
});
Vue.http.interceptors.push(function(request) {
// modify request修改请求 ...
// stop and return respons停止并返回响应e
return request.respondWith(body, {
status: 404,
statusText: 'Not found'
});
});
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
对象公开的,使用它们的名称before
、method
、jsonp
、json
、form
、header
和cors
。
Vue.http.interceptor.before = function(request) {
// override before interceptor拦截器前覆盖
};
The resource service can be used globally 资源服务可以全局使用Vue.resource
or in a Vue instance this.$resource
.Vue.resource
,也可以在Vue实例中使用 this.$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.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
});
}
{
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
});
The Recipes provide code examples to common use-cases. 这些配方提供了常见用例的代码案例。If you want to share your recipe feel free to send a pull request.如果你想分享你的案例,请随时发送拉请求。
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 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
});
}
{
// 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()
}
{
// 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)
}
{
// 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)
}