vue+elementUI+axios實現的全局loading加載動畫


在項目中,很多時候都需要loading加載動畫來緩解用戶的焦慮等待,比如說,我打開了一個頁面,而這個頁面有很多接口請求,但瀏覽器的請求並發數就那么幾個,再加上如果網速不行的話,那么這時候,用戶很可能就會糾結自己到底該不該留下來繼續等待呢。

所以,這時候,loading動畫就是一種緩解等待情緒的方式,當然還有更高端的,比如:骨架屏。有興趣的朋友可以自行研究,我后續也會找機會分享一下。

下面,開始本文的主要內容,目前我在用的是Vue 2.x版本,ajax請求用的是axios,UI框架用的是elementUI。所以下面的loading用的是UI框架中的組件。

嘮叨了這么多,接下來分享一下具體實現的代碼(里面很多代碼邏輯我已經去掉了,只剩下基礎的部分):

代碼可放在main.js中。

import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import axios from 'axios'
 
// loading框設置局部刷新,且所有請求完成后關閉loading框
let loading
let needLoadingRequestCount = 0 // 聲明一個對象用於存儲請求個數
function startLoading () {
  loading = Vue.prototype.$loading({
    lock: true,
    text: '努力加載中...',
    background: 'rgba(0,0,0,0.5)',
    target: document.querySelector('.loading-area') // 設置加載動畫區域
  })
}
function endLoading () {
  loading.close()
}
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}
function hideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
 
// axios
axios.defaults.baseURL = process.env.NODE_ENV === 'production' ? '' : '/api' // 接口基礎路徑
axios.defaults.timeout = 20000 // 超時時間 20s
// axios.defaults.withCredentials = true // 允許設置cookie(開啟的話需后端配置)
// http請求攔截器
axios.interceptors.request.use(config => {
  if (config.isLoading !== false) { // 如果配置了isLoading: false,則不顯示loading
    showFullScreenLoading()
  }
  config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  return config
}, error => {
  hideFullScreenLoading()
  return Promise.reject(error.response)
})
// http響應攔截器
axios.interceptors.response.use(data => {
  hideFullScreenLoading() // 響應成功關閉loading
  return data
}, error => {
  hideFullScreenLoading()
  let _status = error.response && error.response.status
  if (_status === 504 || _status === 404) {
    // 跳轉404頁面(目前沒有,只能先跳轉首頁)
    //router.push({ path: '/' })
  }
  return Promise.reject(error)
})
Vue.prototype.$http = axios

  ok,上面的代碼就實現了全屏的loading動畫。
注意:loading的樣式是可以自定義的,文案也是可以自定義的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM