實現全局loading加載
分析需求,我們只需要在請求發起的時候開始loading,響應結束的時候關閉loading,就這么簡單 對不對?
import axios from 'axios';import { Message, Loading } from 'element-ui';import Cookies from 'js-cookie';import router from '@/router/index'let loading //定義loading變量function startLoading() { //使用Element loading-start 方法 loading = Loading.service({ lock: true, text: '加載中……', background: 'rgba(0, 0, 0, 0.7)' })}function endLoading() { //使用Element loading-close 方法 loading.close()}//那么 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() }}//http request 攔截器axios.interceptors.request.use( config => { var token = '' if(typeof Cookies.get('user') === 'undefined'){ //此時為空 }else { token = JSON.parse(Cookies.get('user')).token }//注意使用的時候需要引入cookie方法,推薦js-cookie config.data = JSON.stringify(config.data); config.headers = { 'Content-Type':'application/json' } if(token != ''){ config.headers.token = token; } showFullScreenLoading() return config; }, error => { return Promise.reject(err); });//http response 攔截器axios.interceptors.response.use( response => { //當返回信息為未登錄或者登錄失效的時候重定向為登錄頁面 if(response.data.code == 'W_100004' || response.data.message == '用戶未登錄或登錄超時,請登錄!'){ router.push({ path:"/", querry:{redirect:router.currentRoute.fullPath}//從哪個頁面跳轉 }) } tryHideFullScreenLoading() return response; }, error => { return Promise.reject(error) })以上這篇vue+axios+element ui 實現全局loading加載示例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答