Skip to content

MessageBox 弹框

模仿系统消息对话框实现的一套模态对话组件,用于消息提示(alert)、确认(confirm)和提交(prompt)。

TIP

引入组件后,可以使用 window.$alertwindow.$confirmwindow.$promptwindow.$msgbox 方法。

引入

html
<script type="module">
  import "./node_modules/easy-component-ui/dist/components/ea-message-box.js";
</script>
js
import "easy-component-ui/ea-message-box";

自定义样式

移步到 CSS PartCSS Custom Properties

消息提示

使用 $alert 打开一个消息提示框,用户必须确认才能关闭。$alert$confirm$prompt 都会返回 Promise,便于链式处理。

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openAlertMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const alertExample = {
  btn: document.querySelector("#openAlertMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      $alert("This is a message", "Title", {
        confirmButtonText: "OK",
      })
        .then(action => {
          $message.info(`action: ${action}`);
        })
        .catch(action => {
          $message.info(`action: ${action}`);
        });
    });
  },
};
alertExample.init();

确认消息

使用 $confirm 询问用户是否继续某一危险或重要操作。

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openconfirmMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const confirmExample = {
  btn: document.querySelector("#openconfirmMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      $confirm("proxy will permanently delete the file. Continue?", "Warning", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        variant: "warning",
      })
        .then(action => {
          $message.info(`action: ${action}`);
        })
        .catch(action => {
          $message.info(`action: ${action}`);
        });
    });
  },
};
confirmExample.init();

提交内容

使用 $prompt 要求用户输入内容(如邮箱),支持正则校验和自定义校验函数。

  • inputPattern:映射到 HTML pattern 属性,命令式 API 也支持传入 RegExp(会自动转换为 .source 字符串)
  • inputValidator:自定义校验函数,返回 true 通过校验,返回 string 作为错误提示,返回 false 使用 inputErrorMessage
  • inputErrorMessage:校验未通过时的错误文本,通过 setCustomValidity 设置
Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openPromptMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const promptExample = {
  btn: document.querySelector("#openPromptMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      $prompt("Please input your e-mail", "Tip", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        inputPattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
        inputErrorMessage: "Invalid Email",
      })
        .then(action => {
          $message.success(`Your email is:${action}`);
        })
        .catch(action => {
          $message.info("Input canceled");
        });
    });
  },
};
promptExample.init();

自定义校验

使用 inputValidator 实现更灵活的校验逻辑,支持异步校验。

Click to open Message Box with Validator
查看代码
html
<div class="demo">
  <ea-button id="openValidatorMessageBox" plain>
    Click to open Message Box with Validator
  </ea-button>
</div>
js
const validatorExample = {
  btn: document.querySelector("#openValidatorMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      $prompt("Please input your name", "Tip", {
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        inputValidator(value) {
          if (!value) return "Name is required";
          if (value.length < 3) return "Name must be at least 3 characters";
          return true;
        },
      })
        .then(action => {
          $message.success(`Your name is: ${action}`);
        })
        .catch(action => {
          $message.info("Input canceled");
        });
    });
  },
};
validatorExample.init();

个性化

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openPersonalizedMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const personalizedExample = {
  btn: document.querySelector("#openPersonalizedMessageBox"),
  init() {
    this.btn.addEventListener("click", () => {
      EaMessageBox({
        heading: "Message",
        message: "This is a message",
        showCancelButton: true,
        confirmButtonText: "OK",
        cancelButtonText: "Cancel",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "Loading...";
            setTimeout(() => {
              done();
              setTimeout(() => {
                instance.confirmButtonLoading = false;
              }, 300);
            }, 3000);
          } else {
            done();
          }
        },
      })
        .then(action => {
          EaMessage({
            variant: "info",
            message: `action: ${action}`,
          });
        })
        .catch(action => {
          EaMessage({
            variant: "info",
            message: `action: ${action}`,
          });
        });
    });
  },
};
personalizedExample.init();

使用 HTML 片段

message 支持传入 HTML 字符串来作为正文内容。

dangerouslyUseHTMLString 属性设置为 truemessage 属性就会被当作 HTML 片段处理。

DANGER

message 属性虽然支持传入 HTML 片段,但是在网站上动态渲染任意 HTML 是非常危险的,因为容易导致 XSS 攻击。因此在 dangerouslyUseHTMLString 打开的情况下,请确保 message 的内容是可信的,永远不要将用户提交的内容赋值给 message 属性。

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openUseHTMLMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const useHTMLExample = {
  btn: document.querySelector("#openUseHTMLMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      EaMessageBox.alert(
        "<strong>proxy is <i>HTML</i> string</strong>",
        "HTML String",
        {
          dangerouslyUseHTMLString: true,
        }
      );
    });
  },
};
useHTMLExample.init();

区分取消操作与关闭操作

有些场景下,点击取消按钮与点击关闭按钮有着不同的含义。

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openDistinguishCancelAndCloseMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const openDistinguishCancelAndCloseExample = {
  btn: document.querySelector("#openDistinguishCancelAndCloseMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      EaMessageBox.confirm(
        "You have unsaved changes, save and proceed?",
        "Confirm",
        {
          distinguishCancelAndClose: true,
          confirmButtonText: "Save",
          cancelButtonText: "Discard Changes",
        }
      )
        .then(() => {
          EaMessage({
            variant: "info",
            message: "Changes saved. Proceeding to a new route.",
          });
        })
        .catch(action => {
          EaMessage({
            variant: "info",
            message:
              action === "cancel"
                ? "Changes discarded. Proceeding to a new route."
                : "Stay in the current route",
          });
        });
    });
  },
};
openDistinguishCancelAndCloseExample.init();

内容居中

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openCenterMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const centerExample = {
  btn: document.querySelector("#openCenterMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      EaMessageBox.confirm(
        "proxy will permanently delete the file. Continue?",
        "Warning",
        {
          confirmButtonText: "OK",
          cancelButtonText: "Cancel",
          variant: "warning",
          center: true,
        }
      )
        .then(() => {
          EaMessage({
            variant: "success",
            message: "Delete completed",
          });
        })
        .catch(() => {
          EaMessage({
            variant: "info",
            message: "Delete canceled",
          });
        });
    });
  },
};
centerExample.init();

可拖放

Click to open Message Box
查看代码
html
<div class="demo">
  <ea-button id="openDraggableMessageBox" plain>
    Click to open Message Box
  </ea-button>
</div>
js
const draggableExample = {
  btn: document.querySelector("#openDraggableMessageBox"),

  init() {
    this.btn.addEventListener("click", () => {
      EaMessageBox.confirm(
        "proxy will permanently delete the file. Continue?",
        "Warning",
        {
          confirmButtonText: "OK",
          cancelButtonText: "Cancel",
          variant: "warning",
          movable: true,
        }
      )
        .then(() => {
          EaMessage({
            variant: "success",
            message: "Delete completed",
          });
        })
        .catch(() => {
          EaMessage({
            variant: "info",
            message: "Delete canceled",
          });
        });
    });
  },
};
draggableExample.init();

EaMessageBox API

EaMessageBox Attributes

参数说明类型可选值默认值
boxType消息框类型String'alert' | 'confirm' | 'prompt' | 'personalized'personalized
headingMessageBox 的标题String
messageMessageBox 的正文内容String
dangerouslyUseHTMLString prop是否将 message 作为 HTML 渲染Booleanfalse
variant消息框变体类型String'primary' | 'success' | 'info' | 'warning' | 'error'
icon自定义图标名称String
closeIcon关闭图标名称Stringxmark
showClose是否显示关闭按钮Booleantrue
distinguishCancelAndClose prop区分取消和关闭操作Booleanfalse
showCancelButton是否显示取消按钮Booleanfalse
showConfirmButton是否显示确认按钮Booleantrue
confirmButtonText确认按钮文本StringOK
cancelButtonText取消按钮文本StringCancel
closeOnClickModal点击遮罩是否关闭Booleantrue
closeOnPressEscape是否可通过按下 ESC 键关闭Booleantrue
showInput是否显示输入框Booleanfalse
inputPlaceholder输入框占位文本String
inputType输入框类型Stringtext
inputValue输入框初始值String
inputPattern prop输入框校验正则(映射到 HTML pattern 属性,命令式 API 也支持传入 RegExp)String
inputValidator prop输入框自定义校验函数,返回 true 通过,返回 string 作为错误信息,返回 false 使用 inputErrorMessageFunction: (value: string) => boolean | string | Promise<boolean | string>
inputErrorMessage输入框校验未通过时的错误文本(通过 setCustomValidity 设置)String
center是否居中内容Booleanfalse
movable是否可拖拽Booleanfalse
roundButton是否使用圆角按钮Booleanfalse
buttonSize按钮尺寸String'small' | 'medium' | 'large'medium
modal是否显示遮罩层Booleantrue
appendToBody是否追加到 bodyBooleanfalse
appendTo追加到指定容器Stringbody
zIndex层级String
backgroundColor遮罩层背景色String
contentWidth内容宽度String
contentMaxWidth内容最大宽度String
contentHeight内容高度String
beforeClose prop关闭前的回调,会暂停关闭过程Function: (done: (cancel?: boolean) => void) => void
confirmButtonLoading prop确认按钮是否加载中Booleanfalse

EaMessageBox CSS Part

名称说明
container容器元素
header头部区域
title-wrap标题包裹元素
type-icon类型图标元素
close-icon关闭图标元素
content内容区域(表单元素)
description描述内容元素
input输入框元素
footer底部区域
confirm-button确认按钮元素
cancel-button取消按钮元素

EaMessageBox Methods

方法名说明参数
show显示消息框
hide隐藏消息框

EaMessageBox Events

事件名说明回调参数(event.detail)
ea-confirm点击确认按钮时触发{}
ea-cancel点击取消按钮时触发{}
ea-message-close当 distinguishCancelAndClose 为 true 时,用户点击关闭按钮触发{}
ea-open遮罩层打开时触发
ea-opened遮罩层打开动画结束时触发
ea-close遮罩层关闭时触发
ea-closed遮罩层关闭动画结束时触发

EaMessageBox CSS Custom Properties

属性名说明默认值
--ea-message-box-padding组件内边距var(--spacing-lg)
--ea-message-box-border-radius组件圆角var(--border-radius-sm)
--ea-message-box-box-shadow组件阴影var(--box-shadow-md)
--ea-message-box-title-font-size标题字号var(--font-size-lg)
--ea-message-box-close-icon-size关闭图标字号var(--font-size-lg)
--ea-message-box-content-font-size内容字号var(--font-size-md)
--ea-message-box-title-color标题颜色var(--grey-900)
--ea-message-box-close-icon-color关闭图标颜色var(--grey-500)
--ea-message-box-content-color内容颜色var(--grey-700)
--ea-message-box-section-gap区域间距var(--spacing-lg)