使用方法
const loader = delayedDisplayLoading('检查中...', 300, this);//第二个参数是this
const res = await checkSettingRule({ materialId: obj.id, deptId: this.currentDeptId }).finally(() => {
loader.hide();//ajax请求完成后务必清理
});
这里有疑问,那页面销毁呢,如何清理
这里就要用到vue2魔法啦,直接看函数实现
// 延迟显示加载中弹窗,默认300毫秒
// vm: 可选参数,传入组件的 this,页面销毁时会自动调用 hide
export const delayedDisplayLoading = (msg = '加载中...', delay = 300, vm = null) => {
uni.hideLoading();
const timer = setTimeout(() => {
uni.showLoading({
title: msg,
mask: true,
});
}, delay);
const hide = () => {
if (timer) {
clearTimeout(timer);
}
uni.hideLoading();
// 如果是手动调用的 hide,需要移除监听器,防止内存残留和重复执行
if (vm && typeof vm.$off === 'function') {
vm.$off('hook:beforeDestroy', hide);
}
};
// 如果传入了 Vue 实例,利用 hook 机制自动绑定销毁事件
if (vm && typeof vm.$once === 'function') {
vm.$once('hook:beforeDestroy', hide);
}
return { hide };
};