以下代码实现了一个增强版的加载状态管理器,主要功能包括Loading状态管理和Toast队列管理,解决了Loading和Toast冲突的问题。
js
/**
* 加载状态管理器(增强版)
* 新增特性:
* 1. Toast队列管理
* 2. 自动处理Loading和Toast的冲突
*/
export const loadingManager = {
_isLoading: false,
_currentLoading: null,
_toastQueue: [], // 待显示的Toast队列
/**
* 显示加载提示
* @param {String} title 提示文字
*/
show: function(title = '加载中...') {
if (this._isLoading) return;
try {
// 清除当前可能存在的Toast
uni.hideToast();
this._currentLoading = uni.showLoading({
title,
mask: true
});
this._isLoading = true;
} catch (e) {
console.error('showLoading error:', e);
}
},
/**
* 隐藏加载提示
* 会自动处理待显示的Toast
*/
hide: function() {
if (!this._isLoading) return;
try {
uni.hideLoading();
} catch (e) {
console.warn('hideLoading error:', e);
} finally {
this._isLoading = false;
this._currentLoading = null;
// 处理队列中的Toast
this._processToastQueue();
}
},
/**
* 切换加载状态
* @param {Boolean} loading 是否显示加载
* @param {String} title 提示文字
*/
toggle: function(loading, title) {
loading ? this.show(title) : this.hide();
},
/**
* 内部方法:处理Toast队列
*/
_processToastQueue: function() {
if (this._toastQueue.length > 0) {
const nextToast = this._toastQueue.shift();
setTimeout(() => {
uni.showToast(nextToast);
// 递归处理剩余Toast
this._processToastQueue();
}, 350); // 适当延迟确保UI过渡
}
},
/**
* 安全显示Toast(新增方法)
* @param {Object} options Toast配置
*/
safeToast: function(options) {
if (this._isLoading) {
// 如果正在loading,将Toast加入队列
this._toastQueue.push(options);
} else {
// 直接显示Toast
uni.showToast(options);
}
}
};
/**
* 增强版Toast提示
* 自动处理与Loading的冲突
* @param {Object} options 配置对象
*/
export const toast = (options) => {
const config = {
icon: 'none',
duration: 2000,
mask: false,
...options
};
// 使用安全版Toast
loadingManager.safeToast(config);
};
使用示例
js
// 引入后再使用
// 显示加载提示
loadingManager.show();
// 隐藏加载提示
loadingManager.hide();
// 显示提示
toast({
//传入配置对象
title: '提示内容'
});