目录
二、页面调用部分(引入上面的popupsServices.js文件)
前言
工作中遇到多个弹窗按顺序弹出,此文针对此业务场景所做的弹窗链的设计思想
一、JS部分(popupsServices.js)
1首先需要需要定义一个全局变量,存放弹窗的唯一标识符KEY值,此数组决定弹窗出现的顺序
const popupOrder = []
class popupsServices {
constructor() {
this.reset();
}
reset() {
this.popups = {}; // 弹窗对象集
this.showIndex = 0; // 当前弹窗下标
}
}
export default new popupsServices();
3.在popupsServices里定义增加弹窗的方法
addPopup(popup) {
if (popup.key && !this.popups[popup.key]) { //如果有弹窗并且弹窗不在弹窗链中,追加进弹窗链
this.popups[popup.key] = popup;
}
if (popupsOrder.includes(popup.key)) { //如果有弹窗并且弹窗不在弹窗链中,在弹窗顺序数组中追加KEY值
popupsOrder.push(popup.key);
}
}
4.在popupsServices里定义初始化弹窗方法
initPopups() {
for (let i = 0; i < popupsOrder.length; i++ ) {
this.popups[popupsOrder[i]].dataPromise = this.popups[popupsOrder[i]].dataGenerator();
}
}
5.在popupsServices里定义弹窗显示方法show() 和next()
show() {
const index = this.showIndex // 当前显示弹窗的下标
if (!(index >= 0 && index < popupsOrder.length)) return;
const popupKey = popupsOrder[index];
const popup = this.popups[popupKey]; // 当前弹窗
if (popup) {
popup.dataPromise.then(() => {
popup.show().then(() => {
this.next();
}).catch((err) => {
this.next();
});
}).catch(() => {
this.next();
});
} else {
this.next();
}
}
next() {
this.showIndex++;
this.show();
}
6.在popupsServices里定义弹窗链开始方法startPopups()
startPopups(restart) {
if (restart) {
this.initPopups();
}
this.show();
}
二、页面调用部分(引入上面的popupsServices.js文件)
1.首先每一个弹窗可看做是一个对象,对象里包括唯一标识符KEY值,数据生成器函数,以及展示函数
示例:首先定义一个弹窗类
class Popup {
constructor({key,dataGenerator,show}) {
this.key = key;
this.dataGenerator = dataGenerator;
this.show = show;
this.dataPromise = null
}
}
2.定义弹窗1
popup1() {
const key = 'popup1';
cosnt dataGenerator = () => new Promise((resolve, reject) => {
// 再此处处理弹窗显示的逻辑
// ........
if ('逻辑显示') {
resolve();
} else {
reject();
}
});
const show = () => new Promise((resovle,reject) => {
// 此处操作弹窗的显示
resovle()
})
return new Popup({ key, dataGenerator, show });
}
3.定义弹窗2
popup2() {
const key = 'popup2';
cosnt dataGenerator = () => new Promise((resolve, reject) => {
// 再此处处理弹窗显示的逻辑
// ........
if ('逻辑显示') {
resolve();
} else {
reject();
}
});
const show = () => new Promise((resovle,reject) => {
// 此处操作弹窗的显示
resovle()
})
return new Popup({ key, dataGenerator, show });
}
.....
4.在合适的生命周期中调用(视情况)
以小程序组件中调用为例
created() { popupsServices.reset(); popupsServices.add(this.popup1); popupsServices.add(this.popup2) } ready() { popupsServices.startPopups(true) }
总结
努力学习中,欢迎朋友们指点指点