ElementUI中LOADING服务无法关闭问题解决
官网解释
需要注意的是,以服务的方式调用的全屏 Loading 是单例的:若在前一个全屏 Loading 关闭前再次调用全屏 Loading,并不会创建一个新的 Loading 实例,而是返回现有全屏 Loading 的实例:
let loadingInstance1 = Loading.service({ fullscreen: true });
let loadingInstance2 = Loading.service({ fullscreen: true });
console.log(loadingInstance1 === loadingInstance2); // true
此时调用它们中任意一个的 close 方法都能关闭这个全屏 Loading。
如果完整引入了 Element,那么Vue.prototype
上会有一个全局方法 $loading
,它的调用方式为:this.$loading(options)
,同样会返回一个 Loading 实例。
但是
有些时候官方的话不能全信!
在网上翻到了一篇文章:
vue+element+axios全局loading增加target标签时处理方法_elloading target-CSDN博客
这位仁兄的代码让我看得头疼,不过原因一看就知道了,于是乎:
let loadingArray = [];
let loadingInstance = null;
//请求拦截
axiosInterceptor.interceptors.request.use(
config => {
/* ... ... */
if (config.loading === true) {
loadingInstance = Loading.service({
lock: true,
text: (config['LOADING_TEXT']?config['LOADING_TEXT']:'正在加载中,请稍后...'),
customClass: 'custom-loading',
target: document.getElementById(config.hasOwnProperty('target')?config['target']:'app-content'),
})
loadingArray.push({key:config.url, value:loadingInstance});
}
}, error => {
nextTick(() => {
for (const loadingStandard of loadingArray) {
loadingStandard.value.close();
}
})
}
//响应拦截
axiosInterceptor.interceptors.response.use(res => {
nextTick(() => {
console.log(loadingArray.length >0);
if (res.config.loading===true) {
for (const loadingStandard of loadingArray) {
if (loadingStandard.key === res.config.url) {
loadingStandard.value.close();
}
}
}
})
}, error => {
nextTick(() => {
for (const loadingStandard of loadingArray) {
loadingStandard.value.close();
}
})
});
不要在意无关代码,主要内容就是:这个loading在使用了target
属性后,不再是单例的了,所以,你可以创建一个数组,使用类似<key,value>的形式将这个loading存储到数组中,然后需要关闭的时候,按照value进行关闭
点赞收藏不迷路!~