近期項目立刻上線,前兩天產品提個需求,加個全局loading,我這半路出家的vue選手,有點懵逼,這玩意仍是第一次,可是做爲一個初級的前端切圖仔,這個東西是必須會的,花了五分鐘思考了一下,而後動鍵盤碼出來 ,今天總結一下,與各位分享交流,有錯誤還請各位指出。css
咱們項目請求使用的是axios,那麼咱們就在請求先後進行攔截,添加咱們須要的東西,而後通訊控制loading,通訊方式我就不寫了,有個老哥寫的不錯,能夠去看看傳送門前端
首先對axios進行封裝 若是你想進行全局錯誤提醒 也能夠在攔截的代碼進行操做 具體代碼看下面vue
/**
* axios 配置模塊
* @module config
* @see utils/request
*/
/**
* axios具體配置對象
* @description 包含了基礎路徑/請求先後對數據對處理,自定義請求頭的設置等
*/
const axiosConfig = {
baseURL: process.env.RESTAPI_PREFIX,
// 請求前的數據處理
// transformRequest: [function (data) {
// return data
// }],
// 請求後的數據處理
// transformResponse: [function (data) {
// return data
// }],
// 自定義的請求頭
// headers: {
// 'Content-Type': 'application/json'
// },
// 查詢對象序列化函數
// paramsSerializer: function (params) {
// return qs.stringify(params)
// },
// 超時設置s
timeout: 10000,
// 跨域是否帶Token 項目中加上會出錯
// withCredentials: true,
// 自定義請求處理
// adapter: function(resolve, reject, config) {},
// 響應的數據格式 json / blob /document /arraybuffer / text / stream
responseType: 'json',
// xsrf 設置
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
// 下傳和下載進度回調
onUploadProgress: function (progressEvent) {
Math.round(progressEvent.loaded * 100 / progressEvent.total)
},
onDownloadProgress: function (progressEvent) {
Math.round(progressEvent.loaded * 100 / progressEvent.total)
},
// 最多轉發數,用於node.js
maxRedirects: 5,
// 最大響應數據大小
maxContentLength: 2000,
// 自定義錯誤狀態碼範圍
validateStatus: function (status) {
return status >= 200 && status < 300
}
// 用於node.js
// httpAgent: new http.Agent({ keepAlive: true }),
// httpsAgent: new https.Agent({ keepAlive: true })
}
/** 導出配置模塊 */
export default axiosConfig
複製代碼
const request = axios.create(config)
node
// 請求攔截器
request.interceptors.request.use(
config => {
// 觸發loading效果
store.dispatch('SetLoding', true)
return config
},
error => {
return Promise.reject(error)
}
)
複製代碼
// 返回狀態判斷(添加響應攔截器)
request.interceptors.response.use(
(res) => {
// 加載loading
store.dispatch('SetLoding', false)
// 若是數據請求失敗
let message = ''
let prefix = res.config.method !== 'get' ? '操做失敗:' : '請求失敗:'
switch (code) {
case 400: message = prefix + '請求參數缺失'; break
case 401: message = prefix + '認證未經過'; break
case 404: message = prefix + '此數據不存在'; break
case 406: message = prefix + '條件不知足'; break
default: message = prefix + '服務器出錯了'; break
}
let error = new Error(message)
if (tip) {
errorTip(vueInstance, error, message)
}
let result = { ...res.data, error: error }
return result
},
(error, a, b) => {
store.dispatch('SetLoding', false)
process.env.NODE_ENV !== 'production' && console.log(error)
return { data: null, code: 500, error: error }
}
)
複製代碼
我這邊通訊用的是Vuex,其餘方式相似ios
state: {
loading: 0
},
mutations: {
SET_LOADING: (state, loading) => {
loading ? ++state.loading : --state.loading
},
CLEAN_LOADING: (state) => {
state.loading = 0
}
},
actions: {
SetLoding ({ commit }, boolean) {
commit('SET_LOADING', boolean)
},
CLEANLOADING ({commit}) {
commit('CLEAN_LOADING')
}
},
getters: {
loading (state) {
return state.loading
}
}
複製代碼
state採用計數方式可以避免一個頁面可能同時有多個ajax請求,致使loading閃現屢次,這樣就會在全部ajax都結束後才隱藏loading,不過有個很重要的地方須要注意,每個路由跳轉時不管ajax是否結束,都必須把state的值設置爲0,具體下面的代碼ajax
router.beforeEach((to, from, next) => {
store.dispatch('CLEANLOADING')
next()
})
複製代碼
全局的loading我這邊是加在home.vue裏,因爲我這個項目是後臺管理,能夠加在layout.vue,其實都差很少vuex
<div class="request-loading" :class="{'request-loading-show':loading}">
<div class="request-loading-main" ></div>
</div>
複製代碼
import { mapGetters } from 'vuex'
export default {
data () {
}
computed: {
...mapState(['loading]) } <style lang="scss" scoped> //這個我就不寫了 loading樣式不一樣 咱們代碼也就不一樣 </style> 複製代碼
大體代碼和思路就是這樣 可能會有錯誤 還但願各位批評指正json