1. 程式人生 > 程式設計 >vue-resource 攔截器interceptors使用詳解

vue-resource 攔截器interceptors使用詳解

前言

攔截器-interceptor

在現代的一些前端框架上,攔截器基本上是很基礎但很重要的一環,比如Angular原生就支援攔截器配置,VUE的Axios模組也給我們提供了攔截器配置,那麼攔截器到底是什麼,它有什麼用?

攔截器能幫助我們解決的

  • 新增統一的request的引數
  • 比如header中加入X-Requested-With,比如客戶端需要實現sign和token的驗證機制,比如你可以寫$http.get(‘/files',params),攔截器幫你拼接成 http://www.xxxx.com/1/files 這樣的請求地址
  • 處理統一的responseError
  • 比如重連機制,拿到error.code錯誤碼重連,比如token過期,重新拿到token再次send request
  • 比如統一報錯資訊,給所有返回的404來個提示也會很酷

在vue專案使用vue-resource實現非同步載入的過程中,需要在任何一個頁面任何一次http請求過程中,增加對token過期的判斷,如果token已過期,需要跳轉至登入頁面。如果要在每個頁面中的http請求操作中新增一次判斷,那將會是一個非常大的修改工作量。那麼vue-resource是否存在一個對於任何一次請求響應捕獲的的公共回撥函式呢?答案是有的!

vue-resource的interceptors攔截器的作用正是解決此需求的妙方。在每次http的請求響應之後,如果設定了攔截器,會優先執行攔截器函式,獲取響應體,然後才會決定是否把response返回給then進行接收。那麼我們可以在這個攔截器裡邊新增對響應狀態碼的判斷,來決定是跳轉到登入頁面還是留在當前頁面繼續獲取資料。

vue-resource 攔截器interceptors使用詳解

安裝與引用

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

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

/*使用VueResource外掛*/
Vue.use(VueResource)

下邊程式碼新增在main.js中

Vue.http.interceptors.push((request,next) => {
 console.log(this)//此處this為請求所在頁面的Vue例項
 // modify request
 request.method = 'POST';//在請求之前可以進行一些預處理和配置

 // continue to next interceptor
  next((response) => {//在響應之後傳給then之前對response進行修改和邏輯判斷。對於token時候已過期的判斷,就新增在此處,頁面中任何一次http請求都會先呼叫此處方法
    response.body = '...';
    return response;

 });
});

攔截器例項

(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,所以使用者是不知道他的操作是成功還是失敗了。這個問題,同樣也可以通過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 攔截器interceptors使用詳解的文章就介紹到這了,更多相關vue-resource攔截器內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!