Message Box
Message Box (메시지 박스)
시스템 메시지 박스를 흉내 낸 일련의 모달 박스로, 주로 정보 알림, 작업 확인, 메시지 프롬프트에 사용해요.
출처: 문서
본문
TIP 설계상 MessageBox는 시스템의
alert,confirm,prompt를 시뮬레이션하므로 내용은 단순해야 해요. 더 복잡한 내용은 Dialog를 사용하세요.
Alert
Alert는 사용자가 확인할 때까지 사용자 작업을 중단시켜요. ElMessageBox.alert 메서드를 호출해서 alert를 열어요. 이는 시스템의 alert를 시뮬레이션하며 ESC를 누르거나 박스 바깥을 클릭해 닫을 수 없어요. 이 예제에서는 message와 title 두 매개변수를 받아요. 박스가 닫힐 때 추가 처리를 위해 Promise 객체를 반환한다는 점을 기억하세요. 대상 브라우저가 Promise를 지원하는지 확실하지 않다면 서드파티 polyfill을 임포트하거나 이 예제처럼 콜백을 사용해야 해요.
Confirm
Confirm은 사용자의 확인을 요청할 때 사용해요. ElMessageBox.confirm 메서드를 호출해서 confirm을 열고, 시스템의 confirm을 시뮬레이션해요. 세 번째 속성인 리터럴 객체 options를 전달해 Message Box를 고도로 커스터마이징할 수도 있어요. 속성 type은 메시지 타입을 나타내며 값은 primary, success, error, info, warning이 될 수 있어요. 두 번째 속성 title은 반드시 문자열이어야 하고, 객체라면 options 속성으로 처리된다는 점에 주의하세요. 여기서는 추가 처리를 위해 Promise를 사용해요. primary는 2.9.11에서 추가되었어요.
Prompt
Prompt는 사용자 입력이 필요할 때 사용해요. ElMessageBox.prompt 메서드를 호출해서 prompt를 열고, 시스템의 prompt를 시뮬레이션해요. inputPattern 매개변수로 자신만의 RegExp 패턴을 지정할 수 있어요. inputValidator로 검증 메서드를 지정하는데, Boolean 또는 String을 반환해야 해요. false 또는 문자열을 반환하면 검증 실패를 뜻하고, 반환된 문자열은 inputErrorMessage로 사용돼요. 추가로 inputPlaceholder 매개변수로 입력 박스의 placeholder를 커스터마이징할 수 있어요.
VNode 사용 (Use VNode)
message는 VNode일 수 있어요.
import { h, ref } from 'vue'
import { ElMessageBox, ElSwitch } from 'element-plus'
const open = () => {
ElMessageBox({
title: 'Message',
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode'),
]),
})
}
const open1 = () => {
const checked = ref(false)
ElMessageBox({
title: 'Message',
// Should pass a function if VNode contains dynamic props
message: () =>
h(ElSwitch, {
modelValue: checked.value,
'onUpdate:modelValue': (val: boolean | string | number) => {
checked.value = val
},
}),
})
}
Action 핸들러와 함께 VNode 사용 (Use VNode With Action Handlers) 2.14.0
message에서 { confirm, cancel, close }를 매개변수로 받을 수 있어요. 이를 통해 커스텀 콘텐츠가 프로그래밍 방식으로 동일한 MessageBox 액션을 트리거하고 인스턴스를 자동으로 닫을 수 있어요.
커스터마이징 (Customization)
다양한 내용을 표시하도록 커스터마이징할 수 있어요. 위에서 언급한 세 메서드는 ElMessageBox 메서드의 재포장이에요. 이 예제는 showCancelButton 속성을 사용해 ElMessageBox 메서드를 직접 호출해요. 이 속성은 취소 버튼 표시 여부를 나타내요. cancelButtonClass로 커스텀 스타일을 추가하고 cancelButtonText로 버튼 텍스트를 커스터마이징할 수 있어요 (confirm 버튼도 같은 필드를 가지며, 전체 필드 목록은 이 문서의 끝에서 확인할 수 있어요). 이 예제는 beforeClose 속성도 사용해요. 이것은 메서드이며 MessageBox 인스턴스가 닫히려고 할 때 트리거되고, 실행되면 닫힘을 중단시켜요. 세 가지 매개변수 action, instance, done을 가져요. 이를 사용하면 인스턴스가 닫히기 전에 조작할 수 있어요. 예를 들어 confirm 버튼에 loading을 활성화할 수 있어요. done 메서드를 호출해서 MessageBox 인스턴스를 닫을 수 있어요 (done이 beforeClose 안에서 호출되지 않으면 인스턴스는 닫히지 않아요).
HTML 문자열 사용 (Use HTML String)
message는 HTML 문자열을 지원해요. dangerouslyUseHTMLString을 true로 설정하면 message를 HTML 문자열로 취급해요.
WARNING
message속성이 HTML 문자열을 지원하기는 하지만, 웹사이트에서 임의의 HTML을 동적으로 렌더링하는 것은 XSS 공격을 유발하기 쉬워 매우 위험해요.dangerouslyUseHTMLString이 켜져 있을 때는message내용이 신뢰할 수 있는지 확인하고,message에 사용자 제공 내용을 절대 할당하지 마세요.
취소와 닫기 구분 (Distinguishing cancel and close)
어떤 경우에는 취소 버튼을 클릭하는 것과 닫기 버튼을 클릭하는 것이 다른 의미를 가질 수 있어요. 기본적으로 Promise의 reject 콜백과 callback의 매개변수는 사용자가 MessageBox를 취소(취소 버튼 클릭)하고 닫을 때(닫기 버튼 또는 마스크 레이어 클릭, ESC 키 누름) 모두 'cancel'이에요. distinguishCancelAndClose를 true로 설정하면 위 두 작업의 매개변수가 각각 'cancel'과 'close'가 돼요.
가운데 정렬 (Centered content)
MessageBox의 내용을 가운데 정렬할 수 있어요. center를 true로 설정하면 내용이 가운데로 정렬돼요.
커스텀 아이콘 (Customized Icon)
아이콘을 어떤 Vue 컴포넌트나 렌더 함수(JSX)로 커스터마이징할 수 있어요.
드래그 가능 (Draggable)
MessageBox는 드래그할 수 있어요. draggable을 true로 설정하면 사용자가 MessageBox를 드래그할 수 있어요. overflow 2.5.4를 true로 설정하면 뷰포트 밖으로 드래그할 수 있어요.
import { ElMessage, ElMessageBox } from 'element-plus'
const open = () => {
ElMessageBox.confirm(
'proxy will permanently delete the file. Continue?',
'Warning',
{
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
draggable: true,
}
)
.then(() => {
ElMessage({
type: 'success',
message: 'Delete completed',
})
})
.catch(() => {
ElMessage({
type: 'info',
message: 'Delete canceled',
})
})
}
const open2 = () => {
ElMessageBox.confirm(
'proxy will permanently delete the file. Continue?',
'Warning',
{
confirmButtonText: 'OK',
cancelButtonText: 'Cancel',
type: 'warning',
draggable: true,
overflow: true,
}
)
.then(() => {
ElMessage({
type: 'success',
message: 'Delete completed',
})
})
.catch(() => {
ElMessage({
type: 'info',
message: 'Delete canceled',
})
})
}
const open3 = () => {
ElMessageBox.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(() => {
ElMessage({
type: 'success',
message: 'Action completed',
})
})
.catch(() => {
ElMessage({
type: 'info',
message: 'Action canceled',
})
})
}
.custom-dragging-message-box.is-dragging {
border: 2px dashed var(--el-color-primary);
opacity: 0.65;
}
전역 메서드 (Global method)
Element Plus를 전체 임포트하면 app.config.globalProperties에 다음 전역 메서드가 추가돼요: $msgbox, $alert, $confirm, $prompt. 그래서 Vue 인스턴스에서 이 페이지에서 했던 것처럼 MessageBox를 호출할 수 있어요. 매개변수는 다음과 같아요:
$msgbox(options)$alert(message, title, options)또는$alert(message, options)$confirm(message, title, options)또는$confirm(message, options)$prompt(message, title, options)또는$prompt(message, options)
앱 컨텍스트 상속 (App context inheritance) > 2.0.4
이제 message box 생성자의 두 번째(변형을 사용하면 네 번째) 매개변수로 컨텍스트를 받아 현재 앱의 컨텍스트를 주입하고 앱의 모든 속성을 상속할 수 있어요.
import { getCurrentInstance } from 'vue'
import { ElMessageBox } from 'element-plus'
// in your setup method
const { appContext } = getCurrentInstance()!
// You can pass it like:
ElMessageBox({}, appContext)
// or if you are using variants
ElMessageBox.alert('Hello world!', 'Title', {}, appContext)
로컬 임포트 (Local import)
MessageBox를 필요할 때 임포트하는 걸 선호한다면:
import { ElMessageBox } from 'element-plus'
해당 메서드는 ElMessageBox, ElMessageBox.alert, ElMessageBox.confirm, ElMessageBox.prompt예요. 매개변수는 위와 같아요.
API
Options
| Name | Description | Type | Default |
|---|---|---|---|
| autofocus | MessageBox를 열 때 자동 포커스 | boolean | true |
| title | MessageBox의 제목 | string | '' |
| message | MessageBox의 내용 | string / VNode / Function 2.2.17 / Function 2.14.0 | — |
| dangerouslyUseHTMLString | message를 HTML 문자열로 취급할지 여부 | boolean | false |
| type | 메시지 타입, 아이콘 표시에 사용 | enum | '' |
| icon | 커스텀 아이콘 컴포넌트, type을 재정의해요 | string / Component | '' |
| closeIcon 2.9.5 | 커스텀 닫기 아이콘 컴포넌트, 기본은 Close | string / Component | '' |
| customClass | MessageBox의 커스텀 클래스 이름 | string | '' |
| customStyle | MessageBox의 커스텀 인라인 스타일 | CSSProperties | {} |
| modal | 마스크 표시 여부 | boolean | true |
| modalClass | 마스크의 커스텀 클래스 이름 | string | — |
| callback | Promise를 선호하지 않는 경우의 MessageBox 닫힘 콜백 | Function | null |
| showClose | MessageBox의 닫기 아이콘 표시 여부 | boolean | true |
| beforeClose | MessageBox가 닫히기 전의 콜백. MessageBox가 닫히는 것을 방지해요 | Function | null |
| distinguishCancelAndClose | MessageBox의 취소와 닫기를 구분할지 여부 | boolean | false |
| lockScroll | MessageBox가 프롬프트될 때 body 스크롤을 잠글지 여부 | boolean | true |
| showCancelButton | 취소 버튼 표시 여부 | boolean | false (confirm과 prompt로 호출 시 true) |
| showConfirmButton | confirm 버튼 표시 여부 | boolean | true |
| cancelButtonText | 취소 버튼의 텍스트 내용 | string | Cancel |
| confirmButtonText | confirm 버튼의 텍스트 내용 | string | OK |
| cancelButtonType 2.13.1 | 취소 버튼의 타입 | enum | — |
| confirmButtonType 2.13.1 | confirm 버튼의 타입 | enum | primary |
| cancelButtonLoadingIcon 2.7.7 | 취소 버튼의 로딩 아이콘 내용 | string / Component | Loading |
| confirmButtonLoadingIcon 2.7.7 | confirm 버튼의 로딩 아이콘 내용 | string / Component | Loading |
| cancelButtonClass | 취소 버튼의 커스텀 클래스 이름 | string | '' |
| confirmButtonClass | confirm 버튼의 커스텀 클래스 이름 | string | '' |
| closeOnClickModal | 마스크 클릭으로 MessageBox를 닫을 수 있는지 여부 | boolean | true (alert로 호출 시 false) |
| closeOnPressEscape | ESC 키로 MessageBox를 닫을 수 있는지 여부 | boolean | true (alert로 호출 시 false) |
| closeOnHashChange | 해시가 변경될 때 MessageBox를 닫을지 여부 | boolean | true |
| showInput | 입력을 표시할지 여부 | boolean | false (prompt로 호출 시 true) |
| inputPlaceholder | 입력의 placeholder | string | '' |
| inputType | 입력의 타입, MDN에서 더 보기 | string | text |
| inputValue | 입력의 초기 값 | string | '' |
| inputPattern | 입력의 정규식 | regexp | null |
| inputValidator | 입력의 검증 함수. boolean 또는 string을 반환해야 해요. 문자열을 반환하면 inputErrorMessage에 할당돼요 |
Function / undefined | undefined |
| inputErrorMessage | 검증 실패 시 오류 메시지 | string | Illegal input |
| center | 내용을 가운데 정렬할지 여부 | boolean | false |
| draggable | MessageBox 드래그 가능 여부 | boolean | false |
| overflow 2.5.4 | 드래그 가능한 MessageBox가 뷰포트를 넘칠 수 있는지 여부 | boolean | false |
| roundButton | 라운드 버튼 사용 여부 | boolean | false |
| buttonSize | confirm과 cancel 버튼의 커스텀 크기 | string | default |
| appendTo 2.2.19 | message box의 루트 요소 설정 | CSSSelector / HTMLElement | — |
더 알아보기 (Learn more)
- Message 컴포넌트 — 전역 메시지
- Notification 컴포넌트 — 전역 알림
- Dialog 컴포넌트 — 대화 상자
- Element Plus 시작하기 — 프로젝트 설정