A set of modal boxes simulating system message box, mainly for alerting information, confirm operations and prompting messages.
TIP
By design MessageBox provides simulations of system's alert, confirm and prompt,so it's content should be simple. For more complicated contents, please use Dialog.
Alert
Alert interrupts user operation until the user confirms.
Open an alert by calling the ElMessageBox.alert method. It simulates the system's alert, and cannot be closed by pressing ESC or clicking outside the box. In this example, two parameters message and title are received. It is worth mentioning that when the box is closed, it returns a Promise object for further processing. If you are not sure if your target browsers support Promise, you should import a third party polyfill or use callbacks instead like this example.
export function MessageBoxAlert() { return ( <ElButton plain onClick={() => { MessageBox.alert("This is a message", "Title", { confirmButtonText: "OK", callback: (result) => { message({ type: "info", message: `action: ${typeof result === "string" ? result : result.action}`, }); }, }); }} > Click to open the Message Box </ElButton> );}
Confirm
Confirm is used to ask users' confirmation.
Call ElMessageBox.confirm method to open a confirm, and it simulates the system's confirm. We can also highly customize Message Box by passing a third attribute options which is a literal object. The attribute type indicates the message type, and it's value can be primary, success, error, info and warning. Note that the second attribute title must be a string, and if it is an object, it will be handled as the attribute options. Here we use Promise to handle further processing. primary has been added in 2.9.11.
export function MessageBoxConfirm() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "proxy will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Click to open the Message Box </ElButton> );}
Prompt
Prompt is used when user input is required.
Call ElMessageBox.prompt method to open a prompt, and it simulates the system's prompt. You can use inputPattern parameter to specify your own RegExp pattern. Use inputValidator to specify validation method, and it should return Boolean or String. Returning false or String means the validation has failed, and the string returned will be used as the inputErrorMessage. In addition, you can customize the placeholder of the input box with inputPlaceholder parameter.
"use client";import { useState } from "react";import { MessageBox } from "@/components/element-plus/message-box";import { message } from "@/components/element-plus/message";import { ElButton } from "@/components/element-plus/button";import { ElSwitch } from "@/components/element-plus/switch";import { Delete } from "@/components/element-plus/generated/icons";import styles from "./feedback.module.css";export function MessageBoxAlert() { return ( <ElButton plain onClick={() => { MessageBox.alert("This is a message", "Title", { confirmButtonText: "OK", callback: (result) => { message({ type: "info", message: `action: ${typeof result === "string" ? result : result.action}`, }); }, }); }} > Click to open the Message Box </ElButton> );}export function MessageBoxConfirm() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "proxy will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Click to open the Message Box </ElButton> );}export function MessageBoxPrompt() { return ( <ElButton plain onClick={() => { MessageBox.prompt("Please input your e-mail", "Tip", { confirmButtonText: "OK", cancelButtonText: "Cancel", inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/, inputErrorMessage: "Invalid Email", }) .then((result) => { const value = typeof result === "object" ? result.value : result; message({ type: "success", message: `Your email is:${value}` }); }) .catch(() => message({ type: "info", message: "Input canceled" })); }} > Click to open Message Box </ElButton> );}function DynamicSwitch() { const [checked, setChecked] = useState(false); return <ElSwitch checked={checked} onCheckedChange={setChecked} />;}export function MessageBoxUseVnode() { return ( <div className={styles.row}> <ElButton plain onClick={() => MessageBox({ title: "Message", message: ( <p> Message can be <i style={{ color: "teal" }}>VNode</i> </p> ), }) } > Common VNode </ElButton> <ElButton plain onClick={() => MessageBox({ title: "Message", message: () => <DynamicSwitch />, }) } > Dynamic props </ElButton> </div> );}export function MessageBoxUseVnodeWithActionHandlers() { return ( <ElButton plain onClick={() => { MessageBox.confirm( ({ confirm, cancel, close }) => ( <div> <p style={{ marginBottom: 8 }}> Custom buttons with MessageBox action handlers </p> <ElButton type="primary" onClick={confirm}>Resolve</ElButton> <ElButton type="danger" onClick={cancel}>Reject</ElButton> <ElButton onClick={close}>Close</ElButton> </div> ), { title: "Message", showConfirmButton: false, showCancelButton: false, distinguishCancelAndClose: true, }, ) .then((action) => message({ type: "success", message: `resolved: ${typeof action === "string" ? action : action.action}`, }), ) .catch((reason) => message({ type: "error", message: `rejected: ${String(reason)}` }), ); }} > Click to open Message Box </ElButton> );}export function MessageBoxCustomization() { return ( <ElButton plain onClick={() => { MessageBox({ title: "Message", message: ( <p> Message can be <i style={{ color: "teal" }}>VNode</i> </p> ), 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((result) => { message({ type: "info", message: `action: ${typeof result === "string" ? result : result.action}`, }); }); }} > Click to open Message Box </ElButton> );}export function MessageBoxUseHtml() { return ( <ElButton plain onClick={() => MessageBox.alert( "<strong>proxy is <i>HTML</i> string</strong>", "HTML String", { dangerouslyUseHTMLString: true }, ) } > Click to open Message Box </ElButton> );}export function MessageBoxDistinguishableCloseCancel() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "You have unsaved changes, save and proceed?", "Confirm", { distinguishCancelAndClose: true, confirmButtonText: "Save", cancelButtonText: "Discard Changes", }, ) .then(() => message({ type: "info", message: "Changes saved. Proceeding to a new route.", }), ) .catch((action) => message({ type: "info", message: action === "cancel" ? "Changes discarded. Proceeding to a new route." : "Stay in the current route", }), ); }} > Click to open Message Box </ElButton> );}export function MessageBoxCenteredContent() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "proxy will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", center: true, }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Click to open Message Box </ElButton> );}export function MessageBoxCustomizedIcon() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "It will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", icon: <Delete />, }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Click to open Message Box </ElButton> );}export function MessageBoxDraggable() { return ( <div className={styles.row}> <ElButton plain onClick={() => { MessageBox.confirm( "proxy will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", draggable: true, }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Open a draggable Message Box </ElButton> <ElButton plain onClick={() => { MessageBox.confirm( "proxy will permanently delete the file. Continue?", "Warning", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "warning", draggable: true, overflow: true, }, ) .then(() => message({ type: "success", message: "Delete completed" })) .catch(() => message({ type: "info", message: "Delete canceled" })); }} > Open a overflow draggable Message Box </ElButton> <ElButton plain onClick={() => { MessageBox.confirm( "This message box has custom dragging styles. Try dragging it to see the effects!", "Custom Dragging Style", { confirmButtonText: "OK", cancelButtonText: "Cancel", type: "info", draggable: true, customClass: "custom-dragging-message-box", }, ) .then(() => message({ type: "success", message: "Action completed" })) .catch(() => message({ type: "info", message: "Action canceled" })); }} > Open a custom dragging style Message Box </ElButton> </div> );}
You can receive { confirm, cancel, close } as parameters in message, which allows custom content to trigger the same MessageBox actions programmatically and automatically close the instance.
The three methods mentioned above are repackagings of the ElMessageBox method. This example calls ElMessageBox method directly using the showCancelButton attribute, which is used to indicate if a cancel button is displayed. Besides we can use cancelButtonClass to add a custom style and cancelButtonText to customize the button text (the confirm button also has these fields, and a complete list of fields can be found at the end of this documentation). This example also uses the beforeClose attribute. It is a method and will be triggered when the MessageBox instance will be closed, and its execution will stop the instance from closing. It has three parameters: action, instance and done. Using it enables you to manipulate the instance before it closes, e.g. activating loading for confirm button; you can invoke the done method to close the MessageBox instance (if done is not called inside beforeClose, the instance will not be closed).
Set dangerouslyUseHTMLString to true and message will be treated as an HTML string.
export function MessageBoxUseHtml() { return ( <ElButton plain onClick={() => MessageBox.alert( "<strong>proxy is <i>HTML</i> string</strong>", "HTML String", { dangerouslyUseHTMLString: true }, ) } > Click to open Message Box </ElButton> );}
WARNING
Although message property supports HTML strings, dynamically rendering arbitrary HTML on your website can be very dangerous because it can easily lead to XSS attacks. So when dangerouslyUseHTMLString is on, please make sure the content of message is trusted, and never assign message to user-provided content.
Distinguishing cancel and close
In some cases, clicking the cancel button and close button may have different meanings.
By default, the parameters of Promise's reject callback and callback are 'cancel' when the user cancels (clicking the cancel button) and closes (clicking the close button or mask layer, pressing the ESC key) the MessageBox. If distinguishCancelAndClose is set to true, the parameters of the above two operations are 'cancel' and 'close' respectively.
export function MessageBoxDistinguishableCloseCancel() { return ( <ElButton plain onClick={() => { MessageBox.confirm( "You have unsaved changes, save and proceed?", "Confirm", { distinguishCancelAndClose: true, confirmButtonText: "Save", cancelButtonText: "Discard Changes", }, ) .then(() => message({ type: "info", message: "Changes saved. Proceeding to a new route.", }), ) .catch((action) => message({ type: "info", message: action === "cancel" ? "Changes discarded. Proceeding to a new route." : "Stay in the current route", }), ); }} > Click to open Message Box </ElButton> );}
If Element Plus is fully imported, it will add the following global methods for app.config.globalProperties: $msgbox, $alert, $confirm and $prompt. So in a Vue instance you can call MessageBox like what we did in this page. The parameters are:
$msgbox(options)
$alert(message, title, options) or $alert(message, options)
$confirm(message, title, options) or $confirm(message, options)
$prompt(message, title, options) or $prompt(message, options)
App context inheritance > 2.0.4
Now message box accepts a context as second (fourth if you are using message box variants) parameter of the message constructor which allows you to inject current app's context to message which allows you to inherit all the properties of the app.
import { getCurrentInstance } from'vue'import { ElMessageBox } from'element-plus'// in your setup methodconst { appContext } =getCurrentInstance()!// You can pass it like:ElMessageBox({}, appContext)// or if you are using variantsElMessageBox.alert('Hello world!', 'Title', {}, appContext)
Local import
If you prefer importing MessageBox on demand:
import { ElMessageBox } from'element-plus'
The corresponding methods are: ElMessageBox, ElMessageBox.alert, ElMessageBox.confirm and ElMessageBox.prompt. The parameters are the same as above.
API
Options
Name
Description
Type
Default
autofocus
auto focus when open MessageBox
boolean
true
title
title of the MessageBox
string
''
message
content of the MessageBox
string / VNode / Function2.2.17 / Function2.14.0
—
dangerouslyUseHTMLString
whether message is treated as HTML string
boolean
false
type
message type, used for icon display
enum
''
icon
custom icon component, overrides type
string / Component
''
closeIcon 2.9.5
custom close icon component, default is Close
string / Component
''
customClass
custom class name for MessageBox
string
''
customStyle
custom inline style for MessageBox
CSSProperties
{}
modal
whether a mask is displayed
boolean
true
modalClass
custom class names for mask
string
—
callback
MessageBox closing callback if you don't prefer Promise
Function
null
showClose
whether to show close icon of MessageBox
boolean
true
beforeClose
callback before MessageBox closes, and it will prevent MessageBox from closing
Function
null
distinguishCancelAndClose
whether to distinguish canceling and closing the MessageBox
boolean
false
lockScroll
whether to lock body scroll when MessageBox prompts
boolean
true
showCancelButton
whether to show a cancel button
boolean
false (true when called with confirm and prompt)
showConfirmButton
whether to show a confirm button
boolean
true
cancelButtonText
text content of cancel button
string
Cancel
confirmButtonText
text content of confirm button
string
OK
cancelButtonType 2.13.1
type of cancel button
enum
—
confirmButtonType 2.13.1
type of confirm button
enum
primary
cancelButtonLoadingIcon 2.7.7
loading icon content of cancel button
string / Component
Loading
confirmButtonLoadingIcon 2.7.7
loading icon content of confirm button
string / Component
Loading
cancelButtonClass
custom class name of cancel button
string
''
confirmButtonClass
custom class name of confirm button
string
''
closeOnClickModal
whether MessageBox can be closed by clicking the mask
boolean
true (false when called with alert)
closeOnPressEscape
whether MessageBox can be closed by pressing the ESC