1. 程式人生 > >vue-resource使用筆記

vue-resource使用筆記

back html 表單 ria 跨域 ble boolean docs table devel

基本語法

//基於全局Vue對象使用http
Vue.http.get(‘/someUrl‘, [options]).then(successCallback, errorCallback);
Vue.http.post(‘/someUrl‘, [body], [options]).then(successCallback, errorCallback);
 
//在一個Vue實例內使用$http
this.$http.get(‘/someUrl‘, [options]).then(successCallback, errorCallback);
this.$http.post(‘/someUrl‘, [body], [options]).then(successCallback, errorCallback);

7種請求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對象

參數

類型

描述

url

string

請求的 URL

method

string

請求的 HTTP 方法,例如:‘GET‘,‘POST‘ 或其他 HTTP

方法

body

Object, FormData string

request body

params

Object

請求的 URL 參數對象

headers

Object

request header

timeout

number

單位為毫秒的請求超時時間 (0 表示無超時時間)

before

function(request)

請求發送前的處理函數,類似於 jQuery beforeSend 函數

progress

function(event)

ProgressEvent 回調處理函數

credentials

boolean

表示跨域請求時是否需要使用憑證

emulateHTTP

boolean

發送 PUT,PATCH,DELETE 請求時以 HTTP POST 的方式發送,並設置請求頭的 X-HTTP-Method-Override

emulateJSON

boolean

request body 以 content-type 為 application/x-www-form-urlencoded 的方式發送

emulateHTTP 的作用

如果Web服務器無法處理 PUT、PATCH 和 DELETE 這種 REST 風格的請求,你可以啟用 enulateHTTP 現象。啟用該選項後,請求會以普通的 POST 方法發出,並且 HTTP 頭信息的 X-HTTP-Method-Override 屬性會設置為實際的 HTTP 方法。

Vue.http.options.emulateHTTP = true;

emulateJSON的作用

如果 Web 服務器無法處理編碼為 application/json 的請求,你可以啟用 emulateJSON 選項。啟用該選項後,請求會以 application/x-www-form-urlencoded 作為 MIME type,就像普通的 HTML 表單一樣。

Vue.http.options.emulateJSON = true;

response 對象

方法

類型

描述

text()

string

string 形式返回 response body

json()

Object

JSON 對象形式返回 response body

blob()

Blob

以二進制形式返回 response body

屬性

類型

描述

ok

boolean

響應的 HTTP 狀態碼在 200~299 之間時,該屬性為 true

status

number

響應的 HTTP 狀態碼

statusText

string

響應的狀態文本

headers

Object

響應頭

全局配置

Vue.http.options.emulateHTTP = true;
Vue.http.options.emulateJSON = true;

Vue.http.interceptors.push(function (request, next) { // ... // 請求發送前的處理邏輯 // ... next(function (response) { // ... // 請求發送後的處理邏輯 // ... // 根據請求的狀態,response 參數會返回給 successCallback 或 errorCallback return response; }); });

上面的配置會對所有請求生效

vue-resource使用筆記