This is the 8th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
Generally, AXIos requests are wrapped, and the file is processed accordingly for interceptors, error codes, global loading, etc.
Project requirements: Use custom.gif icon to achieve global loading effect; In order to avoid manual addition on each page and achieve simple and efficient implementation, vue AXIos interceptor + self-written loading plug-in was finally adopted after consulting information. The code ~ is directly pasted below
I. Global loading is implemented as follows:
Add the loading configuration to the Request interceptor
import { Loading } from 'element-ui'
let loadinginstace;
// Request interceptor
service.interceptors.request.use(
config= > {
loadinginstace = Loading.service({
lock: true.// text: 'Loading',
spinner: 'el-icon-loading'.background: 'rgba (250, 250, 250, 0.8)'.customClass: "osloading".fullscreen: true
})
if (getToken()) {
config.headers['Authorization'] = 'Bearer ' + getToken() // Allow each request to carry a user-defined token. Change the token based on the actual situation
}
return config
},
error= > {
loadinginstace.close()
console.log(error);
Promise.reject(error)
}
);
Copy the code
Loading is then turned off in the response interceptor. The code to turn loading off is loadingInstace.close (), but the problem is that if the request is fast, it will blink. Therefore, a setTimeout can be added to delay the effect, such as adding a 200ms delay below, which will solve the flicker problem.
Another option is to make the background of the mask layer transparent if you feel that the screen will flicker back and forth while switching
// Response interceptor
service.interceptors.response.use(res= > {
setTimeout(() = > {
loadinginstace.close()
}, 200)})Copy the code
2. Modify the loading icon
loadinginstace = Loading.service({
lock: true.// text: 'Loading',
spinner: 'iconfont iconjiazai animal'.background: 'rgba (250, 250, 250, 0.8)'.customClass: "osloading".fullscreen: true
})
.animal{
display: block;
animation: rotate 3s linear infinite;
}
Copy the code
If you just want to change the loading logo color, use the following CSS and write it in app.vue (similar methods are also acceptable)
.el-loading-spinner .path{ stroke:#ed4014! important; } .el-loading-spinner .el-loading-text{ color: #ed4014! important; }Copy the code
Jump to the page in the interceptor
According to different error codes in the interceptor, it is sometimes necessary to jump to different interfaces. The page needs to jump to the interceptor response in the following two ways.
1. Vuex way
window.g_app._store.dispatch({
type: 'login/logout'});Copy the code
2. Direct the switch
location.href = 'login url';
Copy the code