用Axios Element實現全域的請求loading的方法,axiosloading
背景
業務需求是這樣子的,每當發請求到後端時就觸發一個全屏的 loading,多個請求合并為一次 loading。
現在項目中用的是 vue 、axios、element等,所以文章主要是講如果使用 axios 和 element 實現這個功能。
效果如下:
分析
首先,請求開始的時候開始 loading, 然後在請求返回後結束 loading。重點就是要攔截請求和響應。
然後,要解決多個請求合并為一次 loading。
最後,調用element 的 loading 組件即可。
攔截請求和響應
axios 的基本使用方法不贅述。筆者在項目中使用 axios 是以建立執行個體的方式。
// 建立axios執行個體const $ = axios.create({ baseURL: `${URL_PREFIX}`, timeout: 15000})
然後再封裝 post 請求(以 post 為例)
export default { post: (url, data, config = { showLoading: true }) => $.post(url, data, config)}
axios 提供了請求攔截和響應攔截的介面,每次請求都會調用showFullScreenLoading方法,每次響應都會調用tryHideFullScreenLoading()方法
// 請求攔截器$.interceptors.request.use((config) => { showFullScreenLoading() return config}, (error) => { return Promise.reject(error)})// 響應攔截器$.interceptors.response.use((response) => { tryHideFullScreenLoading() return response}, (error) => { return Promise.reject(error)})
那麼showFullScreenLoading tryHideFullScreenLoading()要乾的事兒就是將同一時刻的請求合并。聲明一個變數needLoadingRequestCount,每次調用showFullScreenLoading方法 needLoadingRequestCount + 1。調用tryHideFullScreenLoading()方法,needLoadingRequestCount - 1。needLoadingRequestCount為 0 時,結束 loading。
let needLoadingRequestCount = 0export function showFullScreenLoading() { if (needLoadingRequestCount === 0) { startLoading() } needLoadingRequestCount++}export function tryHideFullScreenLoading() { if (needLoadingRequestCount <= 0) return needLoadingRequestCount-- if (needLoadingRequestCount === 0) { endLoading() }}
startLoading()和endLoading()就是調用 element 的 loading 方法。
import { Loading } from 'element-ui'let loadingfunction startLoading() { loading = Loading.service({ lock: true, text: '載入中……', background: 'rgba(0, 0, 0, 0.7)' })}function endLoading() { loading.close()}
到這裡,準系統已經實現了。每發一個 post 請求,都會顯示全屏 loading。同一時刻的多個請求合并為一次 loading,在所有響應都返回後,結束 loading。
功能增強
實際上,現在的功能還差一點。如果某個請求不需要 loading 呢,那麼發請求的時候加個 showLoading: false的參數就好了。在請求攔截和響應攔截時判斷下該請求是否需要loading,需要 loading 再去調用showFullScreenLoading()方法即可。
在封裝 post 請求時,已經在第三個參數加了 config 對象。config 裡包含了 showloading。然後在攔截器中分別處理。
// 請求攔截器$.interceptors.request.use((config) => { if (config.showLoading) { showFullScreenLoading() } return config})// 響應攔截器$.interceptors.response.use((response) => { if (response.config.showLoading) { tryHideFullScreenLoading() } return response})
我們在調用 axios 時把 config 放在第三個參數中,axios 會直接把 showloading 放在請求攔截器的回調參數裡,可以直接使用。在響應攔截器中的回調參數 response 中則是有一個 config 的 key。這個 config 則是和請求攔截器的回調參數 config 一樣。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。