Notify 플러그인
Notify 플러그인 (Notify Plugin)
Notify는 페이지 위에 떠 있는 애니메이션 메시지를 사용자에게 표시할 수 있는 Quasar 플러그인이에요. 이벤트를 사용자에게 알리는 데 유용하며, 액션을 통해 사용자를 참여시킬 수도 있어요. 토스트(toast) 또는 스낵바(snackbar)라고도 불러요.
출처: 문서
본문
Notify API
Methods
create(opts: object | string): Function알림을 생성해요;$q.notify(...)를 호출하는 것과 같아요. Params:opts(object | string, required) 알림 옵션 Object shape:type(string, optional) (미리 등록된) 타입 또는 기본 제공 타입 중 하나('positive', 'negative', 'warning', 'info', 'ongoing') Examples:'negative','custom-type'color(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'textColor(string, optional) (필요하다면) 텍스트 색상을 덮어써요; Quasar Color Palette에서 가져온 색상 이름 Examples:'primary','teal','teal-10'message(string, optional) 메시지의 내용 Examples:'John Doe pinged you'caption(string, optional) 선택적 캡션의 내용 Examples:'5 minutes ago'html(boolean, optional) 메시지를 HTML로 렌더링해요; 이는 XSS 공격을 유발할 수 있으니, 메시지를 먼저 반드시 살균(sanitize)하세요.icon(string, optional) Quasar 규약에 따른 아이콘 이름; 'img:' 접두사를 사용하지 않는 한 아이콘 라이브러리가 설치되어 있는지 확인하세요. 값으로 'none'(String)을 사용하면 아이콘이 렌더링되지 않아요 (하지만 화면 공간은 여전히 차지해요). Examples:'map','ion-add','img:https://cdn.quasar.dev/logo-v2/svg/logo.svg','img:path/to/some_image.png'iconColor(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'iconSize(string, optional) 단위 이름을 포함한 CSS 단위의 크기 Examples:'16px','2rem'avatar(string, optional) 아바타/이미지의 URL; 제안: public 폴더를 사용하세요. Examples:(public folder) 'img/something.png',(relative path format) require('./my_img.jpg'),(URL) https://some-site.net/some-img.gifspinner(boolean | Component, optional) 업데이트되는 알림에 유용해요; 아바타나 아이콘 대신 Quasar 스피너를 표시해요. 값이 Boolean 'true'이면 기본 QSpinner가 표시돼요. Examples:true,QSpinnerBarsspinnerColor(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'spinnerSize(string, optional) 단위 이름을 포함한 CSS 단위의 크기 Examples:'16px','2rem'position(string, optional), default'bottom'고정할 창의 모서리/측면 Accepts:'top-left','top-right','bottom-left','bottom-right','top','bottom','left','right','center'group(boolean | string | number, optional), defaultmessage + caption + multiline + actions labels + position자동 생성된 그룹을 사용자 정의 그룹으로 덮어써요; 그룹화된 알림은 업데이트할 수 없어요. 문자열 또는 숫자 값은 옵션과 무관하게 특정 그룹의 일부임을 알려줘요. 같은 그룹 이름으로 새 알림이 트리거되면 이전 알림을 대체하고 몇 번 트리거되었는지 뱃지로 표시해요. Examples:'my-group'badgeColor(string, optional) Quasar Color Palette에서 가져온 뱃지의 색상 이름 Examples:'primary','teal','teal-10'badgeTextColor(string, optional) Quasar Color Palette에서 가져온 뱃지 텍스트의 색상 이름 Examples:'primary','teal','teal-10'badgePosition(string, optional), defaulttop-left/top-right뱃지를 붙일 알림의 모서리; 알림이 왼쪽에 있으면 기본값은 top-right이고, 그렇지 않으면 top-left예요. Accepts:'top-left','top-right','bottom-left','bottom-right'badgeStyle(string | any[] | object, optional) 뱃지에 적용할 스타일 정의 Examples:'background-color: #ff0000',{ backgroundColor: '#ff0000' }badgeClass(string | any[] | object, optional) 뱃지에 적용할 클래스 정의 Examples:'my-special-class',{ 'my-special-class': true }progress(boolean, optional) 알림이 언제 자동으로 사라질지를 보여주는 진행 표시줄을 표시해요 (timeout이 0이 아닌 경우).progressClass(string | any[] | object, optional) 진행 표시줄에 적용할 클래스 정의 Examples:'my-special-class',{ 'my-special-class': true }classes(string, optional) 더 쉬운 사용자 정의를 위해 알림에 CSS 클래스를 추가해요 Examples:'my-notif-class'attrs(object, optional) 알림에 설정할 속성의 키-값 Examples:{ role: 'alertdialog' }timeout(number, optional), default5000표시할 시간(밀리초). 0으로 설정하면 자동으로 사라지지 않아요. Examples:2500actions(any[], optional) 알림 액션(버튼); 'noDismiss'가 true가 아니면, 버튼을 클릭/탭하면 알림이 닫혀요. 'closeBtn' 편의 prop도 확인해 보세요. Examples:[{ label: 'Show', handler: () => {}, 'aria-label': 'Button label' }, { icon: 'map', handler: () => {}, color: 'yellow' }, { label: 'Learn more', noDismiss: true, handler: () => {} }]Object shape:handler(Function, optional) 버튼을 클릭/탭했을 때 실행할 함수 Examples:() => { console.log('button clicked') }noDismiss(boolean, optional) 버튼을 클릭/탭해도 알림을 닫지 않아요...(any, optional) 'onClick'을 제외한 다른 모든 QBtn prop ('handler'를 사용하세요) Examples:label: 'Learn more',color: 'primary'
onDismiss(Function, optional) 알림이 닫힐 때 호출할 함수 Examples:() => { console.log('Dismissed') }closeBtn(boolean | string, optional) 'actions' prop을 사용하지 않고 특정 라벨의 닫기 버튼을 추가하는 편리한 방법; true로 설정하면 현재 Quasar 언어에 따라 라벨을 사용해요. Examples:'Close me'multiLine(boolean, optional) 알림을 여러 줄 모드로 전환해요; 이 prop을 사용하지 않고 'action'이 둘 이상 지정되면 기본적으로 여러 줄 모드로 들어가요.ignoreDefaults(boolean, optional) 이 인스턴스에 대해서만 기본 구성(setDefaults()로 설정된)을 무시해요. Returns:Function이 함수를 인자 없이 호출하면 알림을 숨겨요; Object 매개변수 하나를 사용해 호출하면(원본 알림은 그룹화되어 있으면 안 됨), 알림을 업데이트해요(지정된 속성은 이전 속성과 얕게 병합돼요; group과 position은 업데이트 중에 변경할 수 없어서 무시된다는 점에 주의하세요). Function signature:(props?: object) => voidParams:props(object, optional) 그룹화되지 않은 알림을 업데이트하기 위해 이전 속성과 얕게 병합할 알림 속성; ('group'과 'position'을 제외한 객체 속성은 'create()'의 'opts' 매개변수를 참조하세요.)
setDefaults(opts: object): void옵션을 기본값에 병합해요. Params:opts(object, required) 'ignoreDefaults'를 제외한 알림 옵션 (객체 속성은 'create()'의 'opts' 매개변수를 참조하세요)
registerType(typeName: string, typeOpts: object): void새 알림 타입을 등록해요 (또는 기존 것을 덮어써요). Params:typeName(string, required) 타입의 이름 (나중에 'type' prop으로 사용될) Examples:'my-type'typeOpts(object, required) 'ignoreDefaults'를 제외한 알림 옵션 (객체 속성은 'create()'의 'opts' 매개변수를 참조하세요)
Vue Injection
$q.notify로 접근할 수 있어요 (예: Options API에서 this.$q.notify 또는 Composition API에서 useQuasar().notify).
quasar.config.js Options
Configuration key: framework.config.notify (object)
type(string, optional) (미리 등록된) 타입 또는 기본 제공 타입 중 하나('positive', 'negative', 'warning', 'info', 'ongoing') Examples:'negative','custom-type'color(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'textColor(string, optional) (필요하다면) 텍스트 색상을 덮어써요; Quasar Color Palette에서 가져온 색상 이름 Examples:'primary','teal','teal-10'message(string, optional) 메시지의 내용 Examples:'John Doe pinged you'caption(string, optional) 선택적 캡션의 내용 Examples:'5 minutes ago'html(boolean, optional) 메시지를 HTML로 렌더링해요; 이는 XSS 공격을 유발할 수 있으니, 메시지를 먼저 반드시 살균하세요.icon(string, optional) Quasar 규약에 따른 아이콘 이름; 'img:' 접두사를 사용하지 않는 한 아이콘 라이브러리가 설치되어 있는지 확인하세요. 값으로 'none'(String)을 사용하면 아이콘이 렌더링되지 않아요 (하지만 화면 공간은 여전히 차지해요). Examples:'map','ion-add','img:https://cdn.quasar.dev/logo-v2/svg/logo.svg','img:path/to/some_image.png'iconColor(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'iconSize(string, optional) 단위 이름을 포함한 CSS 단위의 크기 Examples:'16px','2rem'avatar(string, optional) 아바타/이미지의 URL; 제안: public 폴더를 사용하세요. Examples:(public folder) 'img/something.png',(relative path format) require('./my_img.jpg'),(URL) https://some-site.net/some-img.gifspinner(boolean | Component, optional) 업데이트되는 알림에 유용해요; 아바타나 아이콘 대신 Quasar 스피너를 표시해요. 값이 Boolean 'true'이면 기본 QSpinner가 표시돼요. quasar.config file type:boolean | stringExamples:true,QSpinnerBarsspinnerColor(string, optional) Quasar Color Palette에서 가져온 컴포넌트의 색상 이름 Examples:'primary','teal','teal-10'spinnerSize(string, optional) 단위 이름을 포함한 CSS 단위의 크기 Examples:'16px','2rem'position(string, optional), default'bottom'고정할 창의 모서리/측면 Accepts:'top-left','top-right','bottom-left','bottom-right','top','bottom','left','right','center'group(boolean | string | number, optional), defaultmessage + caption + multiline + actions labels + position자동 생성된 그룹을 사용자 정의 그룹으로 덮어써요; 그룹화된 알림은 업데이트할 수 없어요. 문자열 또는 숫자 값은 옵션과 무관하게 특정 그룹의 일부임을 알려줘요. 같은 그룹 이름으로 새 알림이 트리거되면 이전 알림을 대체하고 몇 번 트리거되었는지 뱃지로 표시해요. Examples:'my-group'badgeColor(string, optional) Quasar Color Palette에서 가져온 뱃지의 색상 이름 Examples:'primary','teal','teal-10'badgeTextColor(string, optional) Quasar Color Palette에서 가져온 뱃지 텍스트의 색상 이름 Examples:'primary','teal','teal-10'badgePosition(string, optional), defaulttop-left/top-right뱃지를 붙일 알림의 모서리; 알림이 왼쪽에 있으면 기본값은 top-right이고, 그렇지 않으면 top-left예요. Accepts:'top-left','top-right','bottom-left','bottom-right'badgeStyle(string | any[] | object, optional) 뱃지에 적용할 스타일 정의 Examples:'background-color: #ff0000',{ backgroundColor: '#ff0000' }badgeClass(string | any[] | object, optional) 뱃지에 적용할 클래스 정의 Examples:'my-special-class',{ 'my-special-class': true }progress(boolean, optional) 알림이 언제 자동으로 사라질지를 보여주는 진행 표시줄을 표시해요 (timeout이 0이 아닌 경우).progressClass(string | any[] | object, optional) 진행 표시줄에 적용할 클래스 정의 Examples:'my-special-class',{ 'my-special-class': true }classes(string, optional) 더 쉬운 사용자 정의를 위해 알림에 CSS 클래스를 추가해요 Examples:'my-notif-class'attrs(object, optional) 알림에 설정할 속성의 키-값 Examples:{ role: 'alertdialog' }timeout(number, optional), default5000표시할 시간(밀리초). 0으로 설정하면 자동으로 사라지지 않아요.actions(any[], optional) 알림 액션(버튼); 'noDismiss'가 true가 아니면, 버튼을 클릭/탭하면 알림이 닫혀요. 'closeBtn' 편의 prop도 확인해 보세요. Examples:[{ label: 'Show', handler: () => {}, 'aria-label': 'Button label' }, { icon: 'map', handler: () => {}, color: 'yellow' }, { label: 'Learn more', noDismiss: true, handler: () => {} }]Object shape:handler(Function, optional) 버튼을 클릭/탭했을 때 실행할 함수 UI config only; it cannot be set from the quasar.config file. Examples:() => { console.log('button clicked') }noDismiss(boolean, optional) 버튼을 클릭/탭해도 알림을 닫지 않아요...(any, optional) 'onClick'을 제외한 다른 모든 QBtn prop ('handler'를 사용하세요, UI config에서만 가능) Examples:label: 'Learn more',color: 'primary'
onDismiss(Function, optional) 알림이 닫힐 때 호출할 함수 UI config only; it cannot be set from the quasar.config file. Examples:() => { console.log('Dismissed') }closeBtn(boolean | string, optional) 'actions' prop을 사용하지 않고 특정 라벨의 닫기 버튼을 추가하는 편리한 방법; true로 설정하면 현재 Quasar 언어에 따라 라벨을 사용해요. Examples:'Close me'multiLine(boolean, optional) 알림을 여러 줄 모드로 전환해요; 이 prop을 사용하지 않고 'action'이 둘 이상 지정되면 기본적으로 여러 줄 모드로 들어가요.
Installation
quasar.config.js에 추가해요:
framework: {
plugins: [
'Notify'
],
config: {
notify: { /* look at QuasarConfOptions from the API card */ }
}
}
Usage
Basic
Example "Outside of a Vue file":
import { Notify } from 'quasar'
Notify.create('Danger, Will Robinson! Danger!')
// or with a config object:
Notify.create({
message: 'Danger, Will Robinson! Danger!'
})
Example "Inside of a Vue file":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.notify('Message')
// or with a config object:
$q.notify({...})
}
<template>
<q-btn color="purple" @click="showNotif" label="Show Notification" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message: 'Jim pinged you.',
color: 'purple'
})
}
</script>
[!NOTE] If you define any actions, the notification will automatically be dismissed when the user picks it.
With caption
Example "Caption":
<template>
<q-btn color="purple" @click="showNotif" label="Show with caption" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message: 'Jim pinged you.',
caption: '5 minutes ago',
color: 'secondary'
})
}
</script>
With icon, avatar or spinner
Example "With icon":
<template>
<q-btn color="purple" @click="showNotif" label="Show Notification" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message: 'Jim pinged you.',
icon: 'announcement'
})
}
</script>
Example "With avatar":
<template>
<q-btn color="purple" @click="showNotif" label="Show Notification" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message: 'Jim pinged you.',
color: 'purple',
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png'
})
}
</script>
Example "With spinner":
<template>
<div class="row q-gutter-sm">
<q-btn color="purple" @click="showDefault" label="Default spinner" />
<q-btn color="purple" @click="showCustom" label="Custom spinner" />
</div>
</template>
<script setup>
import { QSpinnerGears, useQuasar } from 'quasar'
const $q = useQuasar()
function showDefault() {
$q.notify({
spinner: true,
message: 'Please wait...',
timeout: 2000
})
}
function showCustom() {
$q.notify({
spinner: QSpinnerGears,
message: 'Working...',
timeout: 2000
})
}
</script>
With actions
<template>
<q-btn color="purple" @click="showNotif" label="Show Notifications" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message: 'Jim just pinged you.',
color: 'primary',
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
label: 'Dismiss',
color: 'white',
handler: () => {
/* ... */
}
}
]
})
$q.notify({
message: 'Jim just pinged you.',
color: 'primary',
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
label: 'Reply',
color: 'yellow',
handler: () => {
/* ... */
}
},
{
label: 'Dismiss',
color: 'white',
handler: () => {
/* ... */
}
}
]
})
$q.notify({
message: 'Jim just pinged you.',
color: 'primary',
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
icon: 'close',
color: 'white',
round: true,
handler: () => {
/* ... */
}
}
]
})
}
</script>
Multiline
<template>
<q-btn color="purple" @click="showNotif" label="Show Notification" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message:
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic quisquam non ad sit assumenda consequuntur esse inventore officia. Corrupti reiciendis impedit vel, fugit odit quisquam quae porro exercitationem eveniet quasi.',
color: 'primary',
multiLine: true,
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
label: 'Reply',
color: 'yellow',
handler: () => {
/* ... */
}
}
]
})
}
</script>
Positioning
Example "Positioning & different options":
<template>
<div class="q-gutter-y-sm column items-center">
<div>
<div class="row q-gutter-sm">
<q-btn round size="sm" color="secondary" @click="showNotif('top-left')">
<q-icon name="arrow_back" class="rotate-45" />
</q-btn>
<q-btn round size="sm" color="accent" @click="showNotif('top')">
<q-icon name="arrow_upward" />
</q-btn>
<q-btn
round
size="sm"
color="secondary"
@click="showNotif('top-right')"
>
<q-icon name="arrow_upward" class="rotate-45" />
</q-btn>
</div>
</div>
<div>
<div class="row q-gutter-sm">
<div>
<q-btn round size="sm" color="accent" @click="showNotif('left')">
<q-icon name="arrow_back" />
</q-btn>
</div>
<div>
<q-btn round size="sm" color="accent" @click="showNotif('center')">
<q-icon name="fullscreen_exit" />
</q-btn>
</div>
<div>
<q-btn round size="sm" color="accent" @click="showNotif('right')">
<q-icon name="arrow_forward" />
</q-btn>
</div>
</div>
</div>
<div>
<div class="row q-gutter-sm">
<div>
<q-btn
round
size="sm"
color="secondary"
@click="showNotif('bottom-left')"
>
<q-icon name="arrow_forward" class="rotate-135" />
</q-btn>
</div>
<div>
<q-btn round size="sm" color="accent" @click="showNotif('bottom')">
<q-icon name="arrow_downward" />
</q-btn>
</div>
<div>
<q-btn
round
size="sm"
color="secondary"
@click="showNotif('bottom-right')"
>
<q-icon name="arrow_forward" class="rotate-45" />
</q-btn>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const alerts = [
// ...
]
const $q = useQuasar()
function showNotif(position) {
const { color, textColor, multiLine, icon, message, avatar } =
alerts[Math.floor(Math.random(alerts.length) * 10) % alerts.length]
const random = Math.random() * 100
const twoActions = random > 70
const buttonColor = color ? 'white' : void 0
$q.notify({
color,
textColor,
icon: random > 30 ? icon : null,
message,
position,
avatar,
multiLine,
actions: twoActions
? [
{
label: 'Reply',
color: buttonColor,
handler: () => {
/* console.log('wooow') */
}
},
{
label: 'Dismiss',
color: 'yellow',
handler: () => {
/* console.log('wooow') */
}
}
]
: random > 40
? [
{
label: 'Reply',
color: buttonColor,
handler: () => {
/* console.log('wooow') */
}
}
]
: null,
timeout: Math.random() * 5000 + 3000
})
}
</script>
[!NOTE] For a full list of options, check the API section.
Grouping
Each notification has an underlying unique group which is computed out of the message + caption + multiLine + actions labels + position. When multiple notifications get triggered with the same group, instead of showing all of them and flooding the view, only the first one remains on screen along with a badge. The badge content represents the number of times that the same notification has been triggered (and with same position) since the first one appeared on screen.
However, if you wish to disable this behavior, specify group: false. In the example below, the first button triggers the same notification twice each time is clicked. The second button has grouping disabled. The third button, however, has a custom group name so each subsequent notification replaces the old one and increments the badge number.
<template>
<div class="row q-gutter-sm">
<q-btn no-caps color="teal" @click="triggerTwice" label="Trigger twice" />
<q-btn
no-caps
color="teal"
@click="triggerNoGroupingTwice"
label="Trigger twice (no grouping)"
/>
<q-btn
no-caps
color="teal"
@click="triggerTwiceCustomGroup"
label="Trigger twice (custom group)"
/>
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function triggerTwice() {
$q.notify({
message: 'Jim pinged you.',
color: 'purple'
})
$q.notify({
message: 'Jim pinged you.',
color: 'purple'
})
}
function triggerNoGroupingTwice() {
$q.notify({
group: false,
message: 'Jim pinged you.',
color: 'purple'
})
$q.notify({
group: false,
message: 'Jim pinged you.',
color: 'purple'
})
}
function triggerTwiceCustomGroup() {
$q.notify({
group: 'my-group',
message: 'Jim pinged you.',
color: 'purple'
})
// same group as the previous one,
// so it will replace it and
// increment the badge number:
$q.notify({
group: 'my-group',
message: 'Jack has messaged you.',
color: 'primary'
})
}
</script>
Example "Custom badge":
<template>
<q-btn
no-caps
color="primary"
@click="triggerTwice"
label="Trigger twice with custom badge"
/>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function triggerTwice() {
$q.notify({
message: 'Jim pinged you.',
color: 'purple',
badgeColor: 'yellow',
badgeTextColor: 'dark',
badgeClass: 'shadow-3 glossy my-badge-class'
})
$q.notify({
message: 'Jim pinged you.',
color: 'purple',
badgeColor: 'yellow',
badgeTextColor: 'dark',
badgeClass: 'shadow-3 glossy my-badge-class'
})
}
</script>
<style lang="sass">
.my-badge-class
border: 1px solid #ccc
</style>
Timeout progress
Should you wish, there is a way to tell the user when the notification will disappear from the screen. That's for the cases when timeout is not set to 0.
<template>
<q-btn
no-caps
color="purple"
@click="showNotifs"
label="Show timeout progress"
/>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotifs() {
$q.notify({
progress: true,
message:
'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Hic quisquam non ad sit assumenda consequuntur esse inventore officia. Corrupti reiciendis impedit vel, fugit odit quisquam quae porro exercitationem eveniet quasi.',
color: 'primary',
multiLine: true,
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
label: 'Reply',
color: 'yellow',
handler: () => {
/* ... */
}
}
]
})
setTimeout(() => {
$q.notify({
progress: true,
message: 'Jim emailed you.',
icon: 'mail',
color: 'white',
textColor: 'primary'
})
}, 2000)
setTimeout(() => {
$q.notify({
progress: true,
message: 'Jim pinged you.',
color: 'purple',
avatar: 'https://cdn.quasar.dev/img/boy-avatar.png',
actions: [
{
label: 'Reply',
color: 'yellow',
handler: () => {
/* ... */
}
}
]
})
}, 3200)
}
</script>
Updatable notifications
Should you have an ongoing process and you want to inform the user of its progress without blocking what he is currently doing, then you can generate an updatable notification. It's useful to also show a spinner while at it.
Please note in the example below that we are explicitly setting "group: false" (because only non-grouped notifications can be updated) and "timeout: 0" (because we want to be in full control when the notification will be dismissed).
Example "Updatable":
<template>
<q-btn
no-caps
color="purple"
@click="showNotif"
label="Show updatable notification"
/>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
const notif = $q.notify({
group: false, // required to be updatable
timeout: 0, // we want to be in control when it gets dismissed
spinner: true,
message: 'Uploading file...',
caption: '0%'
})
// we simulate some progress here...
let percentage = 0
const interval = setInterval(() => {
percentage = Math.min(100, percentage + Math.floor(Math.random() * 22))
// we update the dialog
notif({
caption: `${percentage}%`
})
// if we are done...
if (percentage === 100) {
notif({
icon: 'done', // we add an icon
spinner: false, // we reset the spinner setting so the icon can be displayed
message: 'Uploading done!',
timeout: 2500 // we will timeout it in 2.5s
})
clearInterval(interval)
}
}, 500)
}
</script>
Predefined types
There are four predefined types out of the box that you can use: "positive", "negative", "warning" and "info":
Example "Out of the box types":
<template>
<div class="row q-gutter-sm">
<q-btn
no-caps
unelevated
color="positive"
@click="triggerPositive"
label="Trigger 'positive'"
/>
<q-btn
no-caps
unelevated
color="negative"
@click="triggerNegative"
label="Trigger 'negative'"
/>
<q-btn
no-caps
unelevated
color="warning"
text-color="dark"
@click="triggerWarning"
label="Trigger 'warning'"
/>
<q-btn
no-caps
unelevated
color="info"
@click="triggerInfo"
label="Trigger 'info'"
/>
<q-btn
no-caps
unelevated
color="grey-8"
@click="triggerOngoing"
label="Trigger 'ongoing'"
/>
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function triggerPositive() {
$q.notify({
type: 'positive',
message: 'This is a "positive" type notification.'
})
}
function triggerNegative() {
$q.notify({
type: 'negative',
message: 'This is a "negative" type notification.'
})
}
function triggerWarning() {
$q.notify({
type: 'warning',
message: 'This is a "warning" type notification.'
})
}
function triggerInfo() {
$q.notify({
type: 'info',
message: 'This is a "info" type notification.'
})
}
function triggerOngoing() {
// we need to get the notification reference
// otherwise it will never get dismissed ('ongoing' type has timeout 0)
const notif = $q.notify({
type: 'ongoing',
message: 'Looking up the search terms...'
})
// simulate delay
setTimeout(() => {
notif({
type: 'positive',
message: 'Found the results that you were looking for',
timeout: 1000
})
}, 4000)
}
</script>
Furthermore, you can register your own types or even override the predefined ones. The best place to do this would be in a @quasar/app-vite Boot File.
Example "Custom type":
<template>
<div class="row q-gutter-sm">
<q-btn
no-caps
color="brown"
@click="triggerCustomRegisteredType1"
label="Trigger 1"
/>
<q-btn
no-caps
color="primary"
@click="triggerCustomRegisteredType2"
label="Trigger 2"
/>
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
/**
* The reason we have this here
* is that the type needs to be
* registered before using it.
*
* The best place would be a boot file instead
* of a .vue file, otherwise it'll keep on
* registering it every time your component
* gets to be used :)
*/
$q.notify.registerType('my-notif', {
icon: 'announcement',
progress: true,
color: 'brown',
textColor: 'white',
classes: 'glossy'
})
function triggerCustomRegisteredType1() {
$q.notify({
type: 'my-notif',
message: 'This notification is using a custom type.'
})
}
function triggerCustomRegisteredType2() {
// this one overrides some of the original
// options of the "my-notif" registered type
$q.notify({
type: 'my-notif',
icon: 'contactless',
message: 'This notification is using a custom type.',
caption: "It overrides the type's default icon and color.",
color: 'primary'
})
}
</script>
Example "How to register in a boot file":
import { Notify } from 'quasar'
Notify.registerType('my-notif', {
icon: 'announcement',
progress: true,
color: 'brown',
textColor: 'white',
classes: 'glossy'
})
Using HTML
You can use HTML on message if you specify the html: true prop. Please note that this can lead to XSS attacks, so make sure that you sanitize the message by yourself.
Example "Unsafe HTML message":
<template>
<q-btn
no-caps
color="purple"
@click="showNotif"
label="Show HTML Notification"
/>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showNotif() {
$q.notify({
message:
'<em>I can</em> <span style="color: red">use</span> <strong>HTML</strong>',
html: true
})
}
</script>
Setting attributes
You can set custom HTML attributes on the notification itself by setting the attrs Object property. For individual notification actions, you can directly pass them just like any other prop.
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.notify({
// ...
attrs: {
// for the notification itself:
role: 'alertdialog'
},
actions: [
{
icon: 'close',
// for individual action (button):
'aria-label': 'Dismiss'
}
]
})
}
Programmatically closing
Notifications are meant to be dismissed only by the user, however for exceptional cases you can do it programmatically. Especially useful when you set indefinite timeout (0).
const dismiss = $q.notify({...})
...
dismiss()
Setting defaults
There are two ways of setting default configuration that will apply to all Notifications: through quasar.config file > framework > config > notify Object (see Installation section) or programmatically (see below).
// quasar.config file
framework: {
config: {
notify: {
// the config file cannot import components,
// so a spinner is referred to by its name
spinner: 'QSpinnerHourglass'
// ...other Notify options
}
}
}
We'll describe setting the defaults through a @quasar/app-vite Boot File (works the same anywhere in your code, but a boot file ensures this is run before your app starts):
First we create the boot file. Let's name it "notify-defaults.js".
quasar new boot notify-defaults [--format ts]
Add the created notify-defaults.js file to the boot array in the /quasar.config file:
import { defineConfig } from '#q-app'
export default defineConfig(ctx => {
return {
// ...
boot: ['notify-defaults']
// ...
}
})
We then edit the newly created /src/boot/notify-defaults.js:
import { Notify } from 'quasar'
Notify.setDefaults({
timeout: 2500,
textColor: 'white',
actions: [{ icon: 'close', color: 'white' }],
position: 'top-right'
})
[!WARNING] You can only set default
actionsthrough this method. Specifyingactionswith handlers in the/quasar.configfile cannot and will NOT work.
We could also set the defaults in some Vue file:
Example "Inside of a Vue component":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.notify.setDefaults({
position: 'top-right',
timeout: 2500,
textColor: 'white',
actions: [{ icon: 'close', color: 'white' }]
})
}
더 알아보기 (Learn more)
Notify는 상세한 옵션(색상, 아이콘, 아바타, 스피너, 액션, 그룹화, 진행 표시줄, 업데이트 가능한 알림, 사용자 정의 타입 등)을 제공하는 유연한 알림 플러그인이에요. 전체 옵션 목록은 Notify API 섹션을 참조하세요.