Notification
Notification (알림)
페이지 모서리에 전역 알림 메시지를 표시하는 컴포넌트예요.
출처: 문서
본문
기본 사용법 (Basic usage)
Element Plus는 $notify 메서드를 등록했고 이 메서드는 객체를 매개변수로 받아요. 가장 간단한 경우로 알림의 제목과 본문을 위해 title 필드와 message 필드를 설정할 수 있어요. 기본적으로 알림은 4500ms 후 자동으로 닫히지만, duration을 설정해서 지속 시간을 제어할 수 있어요. 특히 0으로 설정하면 자동으로 닫히지 않아요. duration은 밀리초 단위의 Number를 받는다는 점에 유의하세요.
import { h } from 'vue'
import { ElNotification } from 'element-plus'
const open1 = () => {
ElNotification({
title: 'Title',
message: h('i', { style: 'color: teal' }, 'This is a reminder'),
})
}
const open2 = () => {
ElNotification({
title: 'Prompt',
message: 'This is a message that does not automatically close',
duration: 0,
})
}
타입 (With types)
다섯 가지 타입을 제공해요: primary, success, warning, info, error. Element Plus는 다섯 가지 notification 타입을 제공해요: primary, success, warning, info, error. type 필드로 설정하며 다른 값은 무시돼요. 또한 open3, open4처럼 type 필드를 전달하지 않고 바로 호출할 수 있도록 타입별 메서드도 등록했어요. primary는 2.9.11에서 추가되었어요.
import { ElNotification } from 'element-plus'
const open1 = () => {
ElNotification({
title: 'Success',
message: 'This is a success message',
type: 'success',
})
}
const open2 = () => {
ElNotification({
title: 'Warning',
message: 'This is a warning message',
type: 'warning',
})
}
const open3 = () => {
ElNotification.info({
title: 'Info',
message: 'This is an info message',
})
}
const open4 = () => {
ElNotification.error({
title: 'Error',
message: 'This is an error message',
})
}
const open5 = () => {
ElNotification({
title: 'Primary',
message: 'This is a primary message',
type: 'primary',
})
}
커스텀 위치 (Custom position)
Notification은 원하는 어떤 모서리에서도 나타날 수 있어요. position 속성이 Notification이 슬라이드 인할 모서리를 정의해요. top-right, top-left, bottom-right, bottom-left가 될 수 있고, 기본값은 top-right예요.
import { ElNotification } from 'element-plus'
const open1 = () => {
ElNotification({
title: 'Custom Position',
message: "I'm at the top right corner",
})
}
const open2 = () => {
ElNotification({
title: 'Custom Position',
message: "I'm at the bottom right corner",
position: 'bottom-right',
})
}
const open3 = () => {
ElNotification({
title: 'Custom Position',
message: "I'm at the bottom left corner",
position: 'bottom-left',
})
}
const open4 = () => {
ElNotification({
title: 'Custom Position',
message: "I'm at the top left corner",
position: 'top-left',
})
}
오프셋 (With offset)
화면 가장자리에서 Notification의 오프셋을 커스터마이징해요. offset 속성을 설정해서 화면 가장자리에서 Notification의 오프셋을 커스터마이징할 수 있어요. 같은 시점의 모든 Notification 인스턴스는 같은 offset을 가져야 한다는 점에 유의하세요.
HTML 문자열 사용 (Use HTML string)
message는 HTML 문자열을 지원해요. dangerouslyUseHTMLString을 true로 설정하면 message를 HTML 문자열로 취급해요.
WARNING
message속성이 HTML 문자열을 지원하기는 하지만, 웹사이트에서 임의의 HTML을 동적으로 렌더링하는 것은 XSS 공격을 유발하기 쉬워 매우 위험해요.dangerouslyUseHTMLString이 켜져 있을 때는message내용이 신뢰할 수 있는지 확인하고,message에 사용자 제공 내용을 절대 할당하지 마세요.
함수를 사용한 메시지 (Message using functions) 2.9.0
message는 VNode일 수 있어요. 2.9.0 이후부터 message는 VNode를 반환값으로 하는 함수를 지원해요.
import { h, ref } from 'vue'
import { ElNotification, ElSwitch } from 'element-plus'
const open = () => {
ElNotification({
title: 'Use Vnode',
message: h('p', null, [
h('span', null, 'Message can be '),
h('i', { style: 'color: teal' }, 'VNode'),
]),
})
}
const open1 = () => {
const checked = ref(false)
ElNotification({
title: 'Use Vnode',
// Should pass a function if VNode contains dynamic props
message: () =>
h(ElSwitch, {
modelValue: checked.value,
'onUpdate:modelValue': (val: boolean | string | number) => {
checked.value = val
},
}),
})
}
진행 바 (With progress bar) 2.14.4
알림이 자동으로 닫히기까지 남은 시간을 나타내는 진행 바를 표시해요. progress를 true로 설정해서 진행 바를 활성화해요. 진행 바는 duration에 맞춘 카운트다운을 보여줘요. progress에 객체를 전달하면 Progress의 옵션(예: color)으로 커스터마이징할 수 있고, 이는 타입 기반 상태 색상을 재정의해요. pauseOnHover가 true(기본값)일 때 알림 위에 마우스를 올리면 타이머와 진행 바가 모두 일시 정지돼요.
닫기 버튼 숨기기 (Hide close button)
닫기 버튼을 숨길 수 있어요. showClose 속성을 false로 설정하면 사용자가 알림을 닫을 수 없어요.
전역 메서드 (Global method)
Element Plus는 app.config.globalProperties에 전역 메서드 $notify를 추가했어요. 그래서 Vue 인스턴스에서 이 페이지에서 했던 것처럼 Notification을 호출할 수 있어요.
로컬 임포트 (Local import)
import { ElNotification } from 'element-plus'
import { CloseBold } from '@element-plus/icons-vue'
ElNotification({
title: 'Title',
message: 'This is a message',
closeIcon: CloseBold,
})
이 경우 ElNotification(options)으로 호출해야 해요. 타입별 메서드도 등록되어 있어서 예를 들어 ElNotification.success(options)처럼 사용할 수 있어요. ElNotification.closeAll()을 호출해 모든 인스턴스를 수동으로 닫을 수 있어요. 2.10.5에서는 ElNotification.updateOffsets(position)을 호출해 특정 방향의 모든 인스턴스 오프셋을 수동으로 업데이트할 수 있어요.
앱 컨텍스트 상속 (App context inheritance) > 2.0.4
이제 notification 생성자의 두 번째 매개변수로 컨텍스트를 받아 현재 앱의 컨텍스트를 주입하고 앱의 모든 속성을 상속할 수 있어요. 이렇게 사용할 수 있어요:
TIP
ElNotification컴포넌트를 전역 등록했다면 앱 컨텍스트를 자동으로 상속받아요.
import { getCurrentInstance } from 'vue'
import { ElNotification } from 'element-plus'
// in your setup method
const { appContext } = getCurrentInstance()!
ElNotification({}, appContext)
API
Options
| Name | Description | Type | Default |
|---|---|---|---|
| title | 제목 | string | '' |
| message | 설명 텍스트 | string / VNode / Function | '' |
| dangerouslyUseHTMLString | message를 HTML 문자열로 취급할지 여부 | boolean | false |
| type | notification 타입 | enum | '' |
| icon | 커스텀 아이콘 컴포넌트. type에 의해 재정의돼요 | string / Component | — |
| customClass | Notification의 커스텀 클래스 이름 | string | '' |
| duration | 닫힘 전 지속 시간. 0으로 설정하면 자동으로 닫히지 않아요 | number | 4500 |
| position | 커스텀 위치 | enum | top-right |
| showClose | 닫기 버튼 표시 여부 | boolean | true |
| onClose | 닫힐 때의 콜백 함수 | Function | — |
| onClick | 알림이 클릭될 때의 콜백 함수 | Function | — |
| offset | 화면 위쪽 가장자리에서의 오프셋. 같은 시점의 모든 Notification 인스턴스는 같은 offset을 가져야 해요 | number | 0 |
| appendTo | 알림의 루트 요소 설정, 기본값은 document.body | CSSSelector / HTMLElement | — |
| zIndex | 초기 zIndex | number | 0 |
| closeIcon 2.9.8 | 커스텀 닫기 아이콘 | string / Component | Close |
| progress 2.14.4 | 자동 닫힘 카운트다운을 나타내는 진행 바. true로 설정하면 기본 바를 표시하고, Progress 옵션이 담긴 객체를 전달하면 커스터마이징해요 (percentage, type, duration, indeterminate, width는 제외) |
boolean / object | false |
| pauseOnHover 2.14.4 | 알림 위에 마우스를 올렸을 때 타이머를 일시 정지할지 여부 | boolean | true |
Method
Notification과 this.$notify는 현재 Notification 인스턴스를 반환해요. 인스턴스를 수동으로 닫으려면 close를 호출하면 돼요.
| Name | Description | Type |
|---|---|---|
| close | Notification 닫기 | Function |
더 알아보기 (Learn more)
- Message Box 컴포넌트 — 메시지 박스
- Popconfirm 컴포넌트 — 팝컨펌
- Message 컴포넌트 — 전역 메시지
- Element Plus 시작하기 — 프로젝트 설정