vue-resource是Vue提供的體格http請求插件,如同jQuery里的$.ajax,用來和后端交互數據的。
在使用時,首先需要安裝vue-resource插件
1.在項目跟目錄上安裝:
npm install vue-resource
2.引入resource插件
import VueResource from 'vue-resource'; Vue.use(VueResource)
3.發送請求:
this.$http.get("http://www.vrserver.applinzi.com/aixianfeng/apihome.php").then(function(res){ console.log(res) }) ES6寫法:
this.$http.get('url', [options]).then((res) => { // 處理成功的結果}, (res) => { // 處理失敗的結果}); 在發送請求后,使用then方法來處理響應結果,then方法有兩個參數,第一個參數是響應成功時的回調函數,第二個參數是響應失敗時的回調函數。
then方法的回調函數也有兩種寫法,第一種是傳統的函數寫法,第二種是更為簡潔的ES 6的Lambda寫法:
POST請求:
this.$http.post("http://www.vrserver.applinzi.com/aixianfeng/apihome.php",{name:"abc"},{emulateJSON:true}).then( function (res) { // 處理成功的結果 alert(res.body); },function (res) { // 處理失敗的結果 } );JSONP請求:
new Vue({ ready() { this.$http.jsonp('/url', {name:"abc"}) .then(function (res){ console.log(res) }, function (res) { console.log(res) }); } })吐槽一下,現在應該沒有用到JSON的了吧,有的話真呵呵呵了。
支持的HTTP方法
vue-resource的請求API是按照REST風格設計的,它提供了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])除了jsonp以外,另外6種的API名稱是標準的HTTP方法。當服務端使用REST API時,客戶端的編碼風格和服務端的編碼風格近乎一致,這可以減少前端和后端開發人員的溝通成本。
| 客戶端請求方法 | 服務端處理方法 |
|---|---|
| this.$http.get(...) | Getxxx |
| this.$http.post(...) | Postxxx |
| this.$http.put(...) | Putxxx |
| this.$http.delete(...) | Deletexxx |
options對象
發送請求時的options選項對象包含以下屬性:
| 參數 | 類型 | 描述 |
|---|---|---|
| url | string | 請求的URL |
| method | string | 請求的HTTP方法,例如:'GET', 'POST'或其他HTTP方法 |
| body | Object, FormDatastring | request body |
| params | Object | 請求的URL參數對象 |
| headers | Object | request header |
| timeout | number | 單位為毫秒的請求超時時間 (0 表示無超時時間) |
| before | function(request) | 請求發送前的處理函數,類似于jQuery的beforeSend函數 |
| progress | function(event) | ProgressEvent回調處理函數 |
| credientials | boolean | 表示跨域請求時是否需要使用憑證 |
| emulateHTTP | boolean | 發送PUT, PATCH, DELETE請求時以HTTP POST的方式發送,并設置請求頭的X-HTTP-Method-Override |
| emulateJSON | boolean | 將request body以application/x-www-form-urlencoded content type發送 |
新聞熱點
疑難解答
圖片精選