import axios from 'axios'
import Cookies from 'js-cookie'
import {
Loading
} from 'element-ui';
const http = axios.create({
baseURL: "",
timeout: 1000 * 15
})
/**
* 模拟一个出入栈
*/
let loadingInstance = null; // 记录页面中存在的loading
let loadingCount = 0; // 记录当前正在请求的数量
function showLoading(data) {
if (loadingCount === 0) {
loadingInstance = Loading.service({
lock: true,
text: data || '加载中……',
spinner: 'el-icon-loading',
background: 'rgba(0, 0, 0, 0.7)'
});
}
loadingCount++
};
function hideLoading() {
if(loadingInstance && loadingCount != 0) {
loadingCount--
if (loadingCount === 0) {
loadingInstance.close()
loadingInstance = null
}
}
}
/**
* 请求拦截
*/
http.interceptors.request.use(config => {
if (!config.loadingHide) {//有的请求隐藏loading
showLoading(config.loadingText)
}
config.headers['Accept-Language'] = Cookies.get('language') || 'zh-CN'
config.headers['token'] = Cookies.get('token') || ''
return config
}, error => {
return Promise.reject(error)
})
/**
* 响应拦截
*/
http.interceptors.response.use(response => {
if (!response.config.loadingHide) {//有的请求需要隐藏loading
hideLoading()
}
return response
}, error => {
if (!error.config.loadingHide) {//有的请求需要隐藏loading
hideLoading()
}
return Promise.reject(error)
})
axios+element-ui封装全局loading
最新推荐文章于 2024-04-09 14:46:13 发布