实现思路
重写 wx 的 showLoading ,hideLoading ,showToast ,hideLoading
这几个方法, 在使用前添加判断
代码(注意此代码应该在调用原生api之前执行)
//
let isShowLoading = false;
let isShowToast = false;
const { showLoading, hideLoading, showToast, hideToast } = wx;
Object.defineProperty(wx, "showLoading", {
configurable: true, // 是否可以配置
enumerable: true, // 是否可迭代
writable: true, // 是否可重写
value(...param) {
if (isShowToast) {
// Toast优先级更高
return;
}
isShowLoading = true;
return showLoading.apply(this, param); // 原样移交函数参数和this
},
});
Object.defineProperty(wx, "hideLoading", {
configurable: true, // 是否可以配置
enumerable: true, // 是否可迭代
writable: true, // 是否可重写
value(...param) {
if (isShowToast) {
// Toast优先级更高
return;
}
isShowLoading = false;
return hideLoading.apply(this, param); // 原样移交函数参数和this
},
});
Object.defineProperty(wx, "showToast", {
configurable: true, // 是否可以配置
enumerable: true, // 是否可迭代
writable: true, // 是否可重写
value(...param) {
if (isShowLoading) {
// Toast优先级更高
wx.hideLoading();
}
isShowToast = true;
return showToast.apply(this, param); // 原样移交函数参数和this
},
});
Object.defineProperty(wx, "hideToast", {
configurable: true, // 是否可以配置
enumerable: true, // 是否可迭代
writable: true, // 是否可重写
value(...param) {
isShowToast = false;
return hideToast.apply(this, param); // 原样移交函数参数和this
},
});
注意:使用了这个之后会出现一个问题 showToast
之后需要再调用一次 hideToast
不然会出现 loading
不显示 bug
解决办法 (注意:这样会导致 showToast 会在 1.5s 后直接关闭)
return showToast.apply(this, {
...param,
success:() =>{
setTimeout(() => {
wx.hideToast()
},1500)
}
})