標籤: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