vue-resource基本使用方法


一、vue-resource特點

  1、體積小:vue-resource非常小巧,在壓縮以后只有大約12KB,服務端啟用gzip壓縮后只有4.5KB大小,這遠比jQuery的體積要小得多。

  2、支持主流瀏覽器:和Vue.js一樣,vue-resource除了不支持IE 9以下的瀏覽器,其他主流的瀏覽器都支持

  3、支持Promise API和URI Templates:Promise是ES6的特性,Promise的中文含義為“先知”,Promise對象用於異步計算。 URI Templates表示URI模板,有些類似於ASP.NET MVC的路由模板

  4、支持攔截器:攔截器是全局的,攔截器可以在請求發送前和發送請求后做一些處理。 攔截器在一些場景下會非常有用,比如請求發送前在headers中設置access_token,或者在請求失敗時,提供共通的處理方式。

二、安裝與引用

  NPM: npm install vue-resource --save-dev

/*引入Vue框架*/ import Vue from 'vue'
/*引入資源請求插件*/ import VueResource from 'vue-resource'

/*使用VueResource插件*/ Vue.use(VueResource)

  src引入,就直接引入文件即可,注意在要vue之后引入

三、語法

  引入vue-resource后,可以基於全局的Vue對象使用http,也可以基於某個Vue實例使用http

// 基於全局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);

  在發送請求后,使用then方法來處理響應結果,then方法有兩個參數,第一個參數是響應成功時的回調函數,第二個參數是響應失敗時的回調函數。

  then方法的回調函數也有兩種寫法,第一種是傳統的函數寫法,第二種是更為簡潔的ES 6的Lambda寫法:

// 傳統寫法
this.$http.get('/someUrl', [options]).then(function(response){ // 響應成功回調
}, function(response){ // 響應錯誤回調
}); // Lambda寫法
this.$http.get('/someUrl', [options]).then((response) => { // 響應成功回調
}, (response) => { // 響應錯誤回調
});

  1、支持的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時,客戶端的編碼風格和服務端的編碼風格近乎一致,這可以減少前端和后端開發人員的溝通成本。

  2、options對象

  發送請求時的options選項對象包含以下屬性:

  3、emulateHTTP的作用

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

Vue.http.options.emulateHTTP = true;

  4、emulateJSON的作用

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

Vue.http.options.emulateJSON = true;

四、使用實例

var demo = new Vue({ el: '#app', data: { gridColumns: ['customerId', 'companyName', 'contactName', 'phone'], gridData: [], apiUrl: 'http://192.168.118.221:8080/api/customers' }, mounted: function() { this.getCustomers() }, methods: { getCustomers: function() { this.$http.get(this.apiUrl).then((response) => { this.$set('gridData', response.data) },(response) => { console.log("出錯了"); }).catch(function(response) { console.log(response) }) } } });
  這段程序的then方法里提供了successCallbackerrorCallback。catch方法用於捕捉程序的異常,catch方法和errorCallback是不同的,errorCallback只在響應失敗時調用,而catch則是在整個請求到響應過程中,只要程序出錯了就會被調用。
  在then方法的回調函數內,你也可以直接使用this,this仍然是指向Vue實例的。為了減少作用域鏈的搜索,建議使用一個局部變量來接收this。

五、使用resource服務

  vue-resource提供了另外一種方式訪問HTTP——resource服務,resource服務包含以下幾種默認的action

get: {method: 'GET'}, save: {method: 'POST'}, query: {method: 'GET'}, update: {method: 'PUT'}, remove: {method: 'DELETE'}, delete: {method: 'DELETE'}

  1、resource對象也有兩種訪問方式

//全局訪問
Vue.resource //局部訪問
this.$resource

  可以結合URI Template一起使用,以下示例的apiUrl都設置為{/id}了:

apiUrl: 'http://211.149.193.19:8080/api/customers{/id}'

  {/id}相當於一個占位符,當傳入實際的參數時該占位符會被替換。例如,{ id: vm.item.customerId}中的vm.item.customerId為12,那么發送的請求URL為:http://211.149.193.19:8080/api/customers/12

  2、使用實例

//使用get方法發送GET請求,下面這個請求沒有指定{/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); }) } //使用save方法發送POST請求,下面這個請求沒有指定{/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; } //使用update方法發送PUT請求,下面這個請求指定了{/id}
updateCustomer: function() { var resource = this.$resource(this.apiUrl), vm = this; resource.update({ id: vm.item.customerId }, vm.item).then((response) => { vm.getCustomers(); }) }

六、使用inteceptor

  攔截器可以在請求發送前和發送請求后做一些處理。在response返回給successCallback或errorCallback之前,你可以修改response中的內容,或做一些處理。 例如,響應的狀態碼如果是404,你可以顯示友好的404界面。再比如我們就用攔截器做了登錄處理,所以請求發送之前都要通過攔截器驗證當前用戶是否登陸,否則提示登錄頁面。

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

  1、攔截器實例:

  (1)為請求添加loading效果

  通過inteceptor,我們可以為所有的請求處理加一個loading:請求發送前顯示loading,接收響應后隱藏loading。

  具體步驟如下:

//1、添加一個loading組件
<template id='loading-template'>
    <div class='loading-overlay'></div>
</template>

//2、將loading組件作為另外一個Vue實例的子組件
var help = new Vue({ el: '#help', data: { showLoading: false }, components: { 'loading': { template: '#loading-template', } } }) //3、將該Vue實例掛載到某個HTML元素
<div id='help'>
    <loading v-show='showLoading'></loading>
</div>

//4、添加inteceptor
Vue.http.interceptors.push((request, next) => { loading.show = true; next((response) => { loading.show = false; return response; }); });

  我們繼續,當用戶在畫面上停留時間太久時,畫面數據可能已經不是最新的了,這時如果用戶刪除或修改某一條數據,如果這條數據已經被其他用戶刪除了,服務器會反饋一個404的錯誤,但由於我們的put和delete請求沒有處理errorCallback,所以用戶是不知道他的操作是成功還是失敗了。你問我為什么不在每個請求里面處理errorCallback,這是因為我比較懶。這個問題,同樣也可以通過inteceptor解決。

  (2)為請求添加共同的錯誤處理方法

//1、繼續沿用上面的loading組件,在#help元素下加一個對話框
<div id='help'>
    <loading v-show='showLoading' ></loading>
    <modal-dialog :show='showDialog'>
        <header class='dialog-header' slot='header'>
            <h3 class='dialog-title'>Server Error</h3>
        </header>
        <div class='dialog-body' slot='body'>
            <p class='error'>Oops,server has got some errors, error code: {{errorCode}}.</p>
        </div>
    </modal-dialog>
</div>

//2、給help實例的data選項添加兩個屬性
var help = new Vue({ el: '#help', data: { showLoading: false, showDialog: false, errorCode: '' }, components: { 'loading': { template: '#loading-template', } } }) //3、修改inteceptor
Vue.http.interceptors.push((request, next) => { help.showLoading = true; next((response) => { if(!response.ok){ help.errorCode = response.status; help.showDialog = true; } help.showLoading = false; return response; }); });

  vue-resource是一個非常輕量的用於處理HTTP請求的插件,它提供了兩種方式來處理HTTP請求:

  (1)使用Vue.http或this.$http

  (2)使用Vue.resourcethis.$resource

  這兩種方式本質上沒有什么區別,閱讀vue-resource的源碼,你可以發現第2種方式是基於第1種方式實現的。

  提供了攔截器:inteceptor可以在請求前和請求后附加一些行為,這意味着除了請求處理的過程,請求的其他環節都可以由我們來控制。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM