I. Problems encountered
The Loading of Element is invoked as a service, and the DOM node to be overridden is specified by target, so Loading cannot be turned off normally, as shown in the following figure:
Second, solutions
You can detect whether an instance exists before the interceptor invokes a new Loading, and if so, close it. Example: if (loadingInstance) {loadinginstance.close (); }
A complete example of invoking Element Loading as a service
axios.js
File:
import axios from 'axios'
import qs from 'qs'
import { Message, Loading } from "element-ui";
// axios.defaults.baseURL = 'http://localhost:9999' /* the address here is the address of the server that was just started */ /
/ / Loading option
const options = {
text: 'Loading... '.background: 'rgba (255255255,0.6)'.spinner: 'el-icon-loading'.lock: true.target: '.right-container' // target specifies the DOM node to overwrite. The element with the first class named right-container will be retrieved
}
let loadingInstance;
const baseURL = 'http://localhost:9999';
const config = {
withCredentials: true.baseURL: baseURL, // This is the address of the server that was just started
timeout: 2500
}
const urls = ['/banner'.'/personalized'.'/personalized/privatecontent'.'/personalized/newsong'];
const _axios = axios.create(config)
/* Request interception */
_axios.interceptors.request.use(
config= > {
if (config.method === 'post' && !(config.data instanceof FormData)) {
config.headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
config.data = qs.stringify(config.data, { arrayFormat: 'repeat'})}if (loadingInstance) {
loadingInstance.close(); // Since option sets target, a new instance is created each time the target is specified. Therefore, we need to check whether an instance exists before the interceptor invokes a new Loading. If so, we should disable it.
}
if (urls.includes(config.url)) {
loadingInstance = Loading.service(options); // Call Loading as a service
}
return config
}, error => {
return Promise.reject(error)
}
)
/* Response interception */
_axios.interceptors.response.use(
res= > {
if (urls.includes(res.config.url)) {
loadingInstance.close(); / / close the Loading
}
if (res.data.code === 200) {
return res
} else if (res.data.code === 301) {
Message.error("Please log in first.");
} else {
Message.error("Request error")
}
}, err => {
return Promise.resolve(err)
}
)
export default _axios /* Remember to export */
Copy the code
Iv. Attention:
Without target:
When target is added:
Therefore, if target is not used in option to specify the DOM node to be overridden, the if step can be omitted.