vue攔截器Vue.http.interceptors.push

來源:互聯網
上載者:User

標籤:tar   method   actions   from   returns   邏輯   alt   set   down   

剛開始學vue,github上down了一個開源項目,看原始碼的時候看到了這個地方:

/** * @export * @param {any} request * @param {any} next * @returns   */import store from ‘./vuex/store‘// 全域錯誤處理,全域loadingimport { setLoading, setTip } from ‘./vuex/actions/doc_actions‘export default function (request, next) {  if (request.tip !== false) {    setLoading(store, true)  }  next((res) => {    setLoading(store, false)    let data = JSON.parse(res.data)    if (res.status === 0) {      setTip(store, {        text: ‘網路不給力,請稍後再試‘      })    }    if (!data.success) {      setTip(store, {        text: data.error_msg      })    }  })}

 

這是一個全域的攔截器。於是搜尋vue攔截器的用法,下面這一篇寫的不錯:

http://www.cnblogs.com/dupd/p/6048018.html

在vue項目使用vue-resource的過程中,臨時增加了一個需求,需要在任何一個頁面任何一次http請求,增加對token到期的判斷,如果token已到期,需要跳轉至登入頁面。如果要在每個頁面中的http請求操作中添加一次判斷,那麼會是一個非常大的修改工作量。那麼vue-resource是否存在一個對於任何一次請求響應捕獲的的公用回呼函數呢?答案是有的!

vue-resource的interceptors攔截器的作用正是解決此需求的妙方。在每次http的請求響應之後,如果設定了攔截器如下,會優先執行攔截器函數,擷取響應體,然後才會決定是否把response返回給
then進行接收。那麼我們可以在這個攔截器裡邊添加對響應狀態代碼的判斷,來決定是跳轉到登入頁面還是留在當前頁面繼續擷取資料。攔截器詳細介紹》》
下邊代碼添加在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;  });});

 

vue攔截器Vue.http.interceptors.push

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.