首頁  >  文章  >  web前端  >  用Axios Element實作全域的請求loading的方法

用Axios Element實作全域的請求loading的方法

亚连
亚连原創
2018-05-30 10:46:192557瀏覽

本篇文章主要介紹了用Axios Element實現全域的請求loading的方法,現在分享給大家,也給大家做個參考。

背景

業務需求是這樣子的,每當發送請求到後端時就觸發一個全螢幕的 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 = 0

export 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 &#39;element-ui&#39;
let loading
function startLoading() {
 loading = Loading.service({
  lock: true,
  text: &#39;加载中……&#39;,
  background: &#39;rgba(0, 0, 0, 0.7)&#39;
 })
}

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 一樣。


上面是我整理給大家的,希望今後會對大家有幫助。

相關文章:

詳解Vue 全域引入bass.scss 處理方案

js建立二元樹進行數值數組的去重與優化詳解

紅黑樹的插入詳解及Javascript實作方法範例

############################ #######

以上是用Axios Element實作全域的請求loading的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn