CustomDialog,Popup等弹窗如何与页面解耦
在前端开发中,弹窗(如 CustomDialog
、Popup
等)与页面的解耦通常是通过使用事件监听、回调函数、Promise、观察者模式(Observer Pattern)或者依赖注入(Dependency Injection)等设计模式来实现的。以下是一些常见的解耦方法:
.then()
或 .catch()
方法来处理弹窗的结果。这样,页面可以在弹窗关闭后继续执行后续逻辑,而不必直接依赖弹窗的状态。示例代码(以事件监听和回调函数为例):
// 弹窗组件 CustomDialog
class CustomDialog {
constructor(options) {
this.onConfirm = options.onConfirm;
this.onCancel = options.onCancel;
}
show() {
// 显示弹窗的逻辑
}
confirm() {
if (this.onConfirm) {
this.onConfirm();
}
}
cancel() {
if (this.onCancel) {
this.onCancel();
}
}
}
// 页面逻辑
const dialog = new CustomDialog({
onConfirm: () => {
console.log('弹窗已确认');
},
onCancel: () => {
console.log('弹窗已取消');
}
});
dialog.show();
在这个示例中,CustomDialog
组件接受 onConfirm
和 onCancel
两个回调函数作为参数。当用户在弹窗中点击确认或取消按钮时,相应的回调函数会被调用,从而实现与页面的解耦。
弹框类组件需要绑定到对应组件上,由事件触发。对于内容可以使用全局builder,只需定义一次。
定义的语法:
使用方法:
MyGlobalBuilderFunction()
参考链接
自定义弹窗(CustomDialog)
@Builder装饰器:自定义构建函数
Popup控制