實現(xiàn)全局loading加載
分析需求,我們只需要在請求發(fā)起的時候開始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,每次調(diào)用showFullScreenLoading方法 needLoadingRequestCount + 1。 //調(diào)用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() } } //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 實現(xiàn)全局loading加載示例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com