uniapp中uni.showToast和 uni.showLoading同时使用时出现提示中断冲突问题。
以下代码实现了一个增强版的加载状态管理器,主要功能包括Loading状态管理和Toast队列管理,解决了Loading和Toast冲突的问题。
/*** 加载状态管理器(增强版)* 新增特性:* 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 {// 清除当前可能存在的Toastuni.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;// 处理队列中的Toastthis._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);// 递归处理剩余Toastthis._processToastQueue();}, 350); // 适当延迟确保UI过渡}},/*** 安全显示Toast(新增方法)* @param {Object} options Toast配置*/safeToast: function(options) {if (this._isLoading) {// 如果正在loading,将Toast加入队列this._toastQueue.push(options);} else {// 直接显示Toastuni.showToast(options);}}
};/*** 增强版Toast提示* 自动处理与Loading的冲突* @param {Object} options 配置对象*/
export const toast = (options) => {const config = {icon: 'none',duration: 2000,mask: false,...options};// 使用安全版ToastloadingManager.safeToast(config);
};
使用示例
// 引入后再使用
// 显示加载提示
loadingManager.show();
// 隐藏加载提示
loadingManager.hide();
// 显示提示toast({//传入配置对象title: '提示内容'});