安裝:
$ npm install vue-resource
cdn:
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.4.0"></script>
可以使用全局的 Vue.http 或者在 Vue 實例中的 this.$http 調用 http 服務。
使用:
Vue 實例提供了 this.$http 服務可用于發(fā)送 HTTP 請求。 A request method call returns a Promise that resolves to the response. Vue 實例在所有回調方法中都會自動綁定到 this 里。
{
// GET /someUrl
this.$http.get('/someUrl').then((response) => {
// success callback
}, (response) => {
// error callback
});
}
所有的請求類型都可以使用短函數(shù),可以在全局或者 Vue 實例中使用。
// 全局 Vue 對象
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// Vue 實例
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])
選項
| 參數(shù) | 類型 | 描述 |
|---|---|---|
| url | string |
請求發(fā)送到的 URL |
| body |
Object, FormData, string
|
請求中要發(fā)送的數(shù)據(jù) |
| headers | Object |
作為 HTTP 請求頭發(fā)送的 Headers 對象 |
| params | Object |
作為 URL 參數(shù)發(fā)送的 Parameters 對象 |
| method | string |
HTTP 方法 (例如: GET, POST, ...) |
| timeout | number |
請求超時的毫秒數(shù) (0 為不超時) |
| before | function(request) |
在請求發(fā)送之前用于修改請求選項的回調函數(shù) |
| progress | function(event) |
上傳時用于控制 ProgressEvent 的回調函數(shù) |
| credentials | boolean |
Indicates whether or not cross-site Access-Control requests should be made using credentials |
| emulateHTTP | boolean |
使用 HTTP POST 發(fā)送 PUT, PATCH 和 DELETE 請求并設置 X-HTTP-Method-Override 頭 |
| emulateJSON | boolean |
以 application/x-www-form-urlencoded 內容類型發(fā)送請求報文 |
響應
通過下面的屬性和函數(shù)將請求解析為響應對象:
屬性 類型 描述
url string 響應的源 URL
body Object, Blob, string 響應的數(shù)據(jù)報文
headers Header 響應頭對象
ok boolean 從 200 到 299 的 HTTP 狀態(tài)碼
status number 響應中的 HTTP 狀態(tài)碼
statusText string 響應中的 HTTP 狀態(tài)文本
函數(shù) 類型 描述
text() Promise 作為字符串解析報文
json() Promise 作為 Json 對象解析報文
blob() Promise 作為 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
});
}
請求處理
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'
}));
});