vue-resource特點(diǎn):
- 體積小
vue-resource非常小巧,在壓縮以后只有大約12KB,服務(wù)端啟用gzip壓縮后只有4.5KB大小,這遠(yuǎn)比jQuery的體積要小得多。
- 支持主流的瀏覽器
和Vue.js一樣,vue-resource除了不支持IE 9以下的瀏覽器,其他主流的瀏覽器都支持。 - 支持Promise API和URI Templates
Promise是ES6的特性,Promise的中文含義為“先知”,Promise對(duì)象用于異步計(jì)算。
URI Templates表示URI模板,有些類似于ASP.NET MVC的路由模板。 - 支持?jǐn)r截器
攔截器是全局的,攔截器可以在請(qǐng)求發(fā)送前和發(fā)送請(qǐng)求后做一些處理。
攔截器在一些場(chǎng)景下會(huì)非常有用,比如請(qǐng)求發(fā)送前在headers中設(shè)置access_token,或者在請(qǐng)求失敗時(shí),提供共通的處理方式。
基本語(yǔ)法
引入vue-resource后,可以基于全局的Vue對(duì)象使用http,也可以基于某個(gè)Vue實(shí)例使用http。
// 基于全局Vue對(duì)象使用http
Vue.http.get('/someUrl', [options]).then(successCallback, errorCallback);
Vue.http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
// 在一個(gè)Vue實(shí)例內(nèi)使用$http
this.$http.get('/someUrl', [options]).then(successCallback, errorCallback);
this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCallback);
在發(fā)送請(qǐng)求后,使用then方法來(lái)處理響應(yīng)結(jié)果,then方法有兩個(gè)參數(shù),第一個(gè)參數(shù)是響應(yīng)成功時(shí)的回調(diào)函數(shù),第二個(gè)參數(shù)是響應(yīng)失敗時(shí)的回調(diào)函數(shù)。
then方法的回調(diào)函數(shù)也有兩種寫法,第一種是傳統(tǒng)的函數(shù)寫法,第二種是更為簡(jiǎn)潔的ES 6的Lambda寫法:
// 傳統(tǒng)寫法
this.$http.get('/someUrl', [options]).then(function(response){
// 響應(yīng)成功回調(diào)
}, function(response){
// 響應(yīng)錯(cuò)誤回調(diào)
});
// Lambda寫法
this.$http.get('/someUrl', [options]).then((response) => {
// 響應(yīng)成功回調(diào)
}, (response) => {
// 響應(yīng)錯(cuò)誤回調(diào)
});
vue-resource的請(qǐng)求API是按照REST風(fēng)格設(shè)計(jì)的,它提供了7種請(qǐng)求API:
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對(duì)象
發(fā)送請(qǐng)求時(shí)的options選項(xiàng)對(duì)象包含以下屬性:
| 參數(shù) | 類型 | 描述 |
|---|---|---|
| url | string | 請(qǐng)求的URL |
| method | string | 請(qǐng)求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 |
| body | Object,FormDatastring | request body |
| params | Object | 請(qǐng)求的URL參數(shù)對(duì)象 |
| headers | Object | request header |
| timeout | number | 單位為毫秒的請(qǐng)求超時(shí)時(shí)間 (0 表示無(wú)超時(shí)時(shí)間) |
| before | function(request) | 請(qǐng)求發(fā)送前的處理函數(shù),類似于jQuery的beforeSend函數(shù) |
| progress | function(event) | ProgressEvent回調(diào)處理函數(shù) |
| credientials | boolean | 表示跨域請(qǐng)求時(shí)是否需要使用憑證 |
| emulateHTTP | boolean | 發(fā)送PUT, PATCH, DELETE請(qǐng)求時(shí)以HTTP POST的方式發(fā)送,并設(shè)置請(qǐng)求頭的X-HTTP-Method-Override |
| emulateJSON | boolean | 將request body以application/x-www-form-urlencoded content type發(fā)送 |
emulateHTTP的作用
如果Web服務(wù)器無(wú)法處理PUT, PATCH和DELETE這種REST風(fēng)格的請(qǐng)求,你可以啟用enulateHTTP現(xiàn)象。啟用該選項(xiàng)后,請(qǐng)求會(huì)以普通的POST方法發(fā)出,并且HTTP頭信息的X-HTTP-Method-Override屬性會(huì)設(shè)置為實(shí)際的HTTP方法。
Vue.http.options.emulateHTTP = true;
emulateJSON的作用
如果Web服務(wù)器無(wú)法處理編碼為application/json的請(qǐng)求,你可以啟用emulateJSON選項(xiàng)。啟用該選項(xiàng)后,請(qǐng)求會(huì)以application/x-www-form-urlencoded作為MIME type,就像普通的HTML表單一樣。
Vue.http.options.emulateJSON = true;
response對(duì)象
response對(duì)象包含以下屬性:
| 方法 | 類型 | 描述 |
|---|---|---|
| text() | string | 以string形式返回response body |
| json() | Object | 以JSON對(duì)象形式返回response body |
| blob() | Blob | 以二進(jìn)制形式返回response body |
| 屬性 | 類型 | 描述 |
| ok | boolean | 響應(yīng)的HTTP狀態(tài)碼在200~299之間時(shí),該屬性為true |
| status | number | 響應(yīng)的HTTP狀態(tài)碼 |
| statusText | string | 響應(yīng)的狀態(tài)文本 |
| headers | Object | 響應(yīng)頭 |
代碼示例
1.get
vm.$http.get(this.apiUrl)
.then((response) => {
this.$set('gridData', response.data)
})
.catch(function(response) {
console.log(response)
})
2.post
vm.$http.post(vm.apiUrl, {},{emulateJSON:true})
.then((response) => {
})
3.delect
vm.$http.delete(this.apiUrl )
.then((response) => {
})
4.put
vm.$http.put(this.apiUrl)
.then((response) => {
})
5.jsonp
vm.$http.jsonp(this.apiUrl)
.then(function(response){
})
使用resource服務(wù)
vue-resource提供了另外一種方式訪問(wèn)HTTP——resource服務(wù),resource服務(wù)包含以下幾種默認(rèn)的action:
get: {method: 'GET'},
save: {method: 'POST'},
query: {method: 'GET'},
update: {method: 'PUT'},
remove: {method: 'DELETE'},
delete: {method: 'DELETE'}
resource對(duì)象也有兩種訪問(wèn)方式:
全局訪問(wèn):Vue.resource
實(shí)例訪問(wèn):this.$resource
resource可以結(jié)合URI Template一起使用,以下示例的apiUrl都設(shè)置為{/id}了:
apiUrl: 'http://211.149.193.19:8080/api/customers{/id}'
GET請(qǐng)求
使用get方法發(fā)送GET請(qǐng)求,下面這個(gè)請(qǐng)求沒(méi)有指定{/id}
getCustomers: function() {
var resource = this.$resource(this.apiUrl)
vm = this
resource.get()
.then((response) => {
vm.$set('gridData', response.data)
})
.catch(function(response) {
console.log(response)
})
}
POST請(qǐng)求
使用save方法發(fā)送POST請(qǐng)求,下面這個(gè)請(qǐng)求沒(méi)有指定{/id}
createCustomer: function() {
var resource = this.$resource(this.apiUrl)
vm = this
resource.save(vm.apiUrl, vm.item)
.then((response) => {
vm.$set('item', {})
vm.getCustomers()
})
this.show = false
}
PUT請(qǐng)求
使用update方法發(fā)送PUT請(qǐng)求,下面這個(gè)請(qǐng)求指定了{(lán)/id}
。
updateCustomer: function() {
var resource = this.$resource(this.apiUrl)
vm = this
resource.update({ id: vm.item.customerId}, vm.item)
.then((response) => {
vm.getCustomers()
})
}
DELETE請(qǐng)求
使用remove或delete方法發(fā)送DELETE請(qǐng)求,下面這個(gè)請(qǐng)求指定了{(lán)/id}
。
deleteCustomer: function(customer){
var resource = this.$resource(this.apiUrl)
vm = this
resource.remove({ id: customer.customerId})
.then((response) => {
vm.getCustomers()
})
}
攔截器
在vue項(xiàng)目使用vue-resource的過(guò)程中,臨時(shí)增加了一個(gè)需求,需要在任何一個(gè)頁(yè)面任何一次http請(qǐng)求,增加對(duì)token過(guò)期的判斷,如果token已過(guò)期,需要跳轉(zhuǎn)至登錄頁(yè)面。如果要在每個(gè)頁(yè)面中的http請(qǐng)求操作中添加一次判斷,那么會(huì)是一個(gè)非常大的修改工作量。那么vue-resource是否存在一個(gè)對(duì)于任何一次請(qǐng)求響應(yīng)捕獲的的公共回調(diào)函數(shù)呢?答案是有的!
vue-resource的interceptors攔截器的作用正是解決此需求的妙方。在每次http的請(qǐng)求響應(yīng)之后,如果設(shè)置了攔截器如下,會(huì)優(yōu)先執(zhí)行攔截器函數(shù),獲取響應(yīng)體,然后才會(huì)決定是否把response返回給
then進(jìn)行接收。那么我們可以在這個(gè)攔截器里邊添加對(duì)響應(yīng)狀態(tài)碼的判斷,來(lái)決定是跳轉(zhuǎn)到登錄頁(yè)面還是留在當(dāng)前頁(yè)面繼續(xù)獲取數(shù)據(jù)。
下邊代碼添加在main.js中
Vue.http.interceptors.push((request, next) => {
console.log(this)//此處this為請(qǐng)求所在頁(yè)面的Vue實(shí)例
// modify request
request.method = 'POST';//在請(qǐng)求之前可以進(jìn)行一些預(yù)處理和配置
// continue to next interceptor
next((response) => {//在響應(yīng)之后傳給then之前對(duì)response進(jìn)行修改和邏輯判斷。對(duì)于token時(shí)候已過(guò)期的判斷,就添加在此處,頁(yè)面中任何一次http請(qǐng)求都會(huì)先調(diào)用此處方法
response.body = '...';
return response;
});
});