다이얼로그 플러그인
다이얼로그 플러그인 (Dialog Plugin)
Quasar 다이얼로그는 사용자에게 특정 동작이나 동작 목록을 선택할 수 있는 능력을 제공하는 훌륭한 방법이에요. 또한 사용자에게 중요한 정보를 제공하거나, 결정(또는 여러 결정)을 요구할 수도 있어요.
UI 관점에서 다이얼로그는 화면의 일부만 덮는 일종의 떠 있는 모달로 생각할 수 있어요. 즉, 다이얼로그는 빠른 사용자 동작에만 사용해야 해요.
[!NOTE] 다이얼로그는 Vue 파일 템플릿에서 컴포넌트로도 사용할 수 있어요(특정 폼 컴포넌트, 선택 가능한 옵션 같은 복잡한 사용 사례용). 이 경우 QDialog 페이지로 이동하세요.
Quasar 플러그인으로 다이얼로그를 사용하는 것이 QDialog 컴포넌트보다 나은 점은, 플러그인은 Vue 공간 밖에서도 호출할 수 있고 템플릿을 관리할 필요가 없다는 거예요. 하지만 결과적으로 커스터마이징은 컴포넌트 버전에 비할 수 없어요.
그러나 Dialog 플러그인이 렌더링할 컴포넌트를 제공할 수도 있어요("커스텀 컴포넌트 호출" 섹션 참고). 이는 Vue 템플릿을 인라인 다이얼로그로 어지럽히는 것을 피하는 좋은 방법이에요(프로젝트 파일을 더 잘 구성하고 다이얼로그를 재사용하는 데도 도움이 돼요).
QDialog 플러그인으로 다음 폼 콘텐츠를 가진 세 가지 유형의 다이얼로그를 프로그래밍 방식으로 만들 수 있어요:
- 프롬프트 다이얼로그 - 사용자에게 입력 필드에 어떤 데이터를 채우도록 요청해요.
- 사용자가 라디오 버튼이나 토글(단일 선택 전용) 또는 체크 박스(다중 선택용)로 선택할 수 있는 옵션 집합.
- 특정 동작이나 입력에 대해 취소하거나 "확인"할 수 있는 간단한 확인 다이얼로그.
#1(프롬프트 입력 폼)을 만들려면 opts 객체 안에 prompt 속성이 있어요.
#2(옵션 선택 폼)을 만들려면 opts 객체 안에 options 속성이 있어요.
출처: 문서
본문
Dialog API
Methods (메서드)
create(opts: object): object임시(ad-hoc) 다이얼로그를 만들어요; $q.dialog(...)을 호출하는 것과 같아요 파라미터:opts(object, required) 다이얼로그 옵션 객체 형태:class(string | any[] | object, optional) 다이얼로그의 QCard에 적용할 CSS 클래스 이름 예시:'my-class'style(string | any[] | object, optional) 다이얼로그의 QCard에 적용할 CSS 스타일 예시:'border: 2px solid black'title(string, optional) 다이얼로그의 제목을 위한 텍스트 예시:'Continue?'message(string, optional) 입력하거나, 선택하거나, 확인해야 할 것에 대한 더 많은 정보를 담은 텍스트 예시:'Are you certain you want to continue?'html(boolean, optional) title과 message를 HTML로 렌더링해요; XSS 공격으로 이어질 수 있으므로 메시지를 먼저 꼭 소독(sanitize)하세요position(string, optional), 기본값'standard'화면에서 다이얼로그의 위치. standard는 중앙이에요. 허용값:'top','right','bottom','left','standard'prompt(object, optional) 질문 프롬프트를 위한 입력 필드의 객체 정의 예시:{ model: 'initial-value', type: 'number' }객체 형태:model(string, required) 입력의 초기 값type(string, optional), 기본값'text'입력 필드 유형을 결정하는 선택 속성 예시:'text','number','textarea'isValid(Function, optional) 입력된 콘텐츠가 유효한가요? 함수 시그니처:(val: string) => boolean파라미터:val(string, required) 입력의 값 반환:boolean텍스트가 검증을 통과했는지 여부
...QInputProps(any, optional) color, label, stackLabel, filled, outlined, rounded, prefix 등 어떤 QInput props든 예시:label: 'My Label',standout: true,counter: true,maxlength: 12...nativeAttributes(object, optional) 프롬프트 컨트롤에 전달할 네이티브 속성 예시:autocomplete: 'off'
options(object, optional) 선택 폼 콘텐츠를 만들기 위한 객체 정의 예시:{ model: null, type: 'radio', items: [ /* ...listOfItems */ ] }객체 형태:model(string | any[], required) 선택의 값(radio 타입이면 String, 아니면 Array) 예시:[]type(string, optional), 기본값'radio'선택의 유형 허용값:'radio','checkbox','toggle'items(any[], optional) 상호작용할 옵션 목록; QOptionGroup 컴포넌트의 options prop에 해당 예시:[{ label: 'Option 1', value: 'op1' }, { label: 'Option 2', value: 'op2' }, { label: 'Option 3', value: 'op3' }]
isValid(Function, optional) 모델이 유효한가요? 함수 시그니처:(model: string | any[]) => boolean파라미터:model(string | any[], required) 현재 모델(radio 타입이면 String, 아니면 Array) 예시:'opt2'['opt1'][]['opt1', 'opt3']반환:boolean선택이 검증을 통과했는지 여부
...QOptionGroupProps(any, optional) 어떤 QOptionGroup props든 예시:color: 'deep-purple-4',inline: true,dense: true,leftLabel: true...nativeAttributes(object, optional) 내부 QOptionGroup에 전달할 네이티브 속성
progress(boolean | object, optional) Quasar 스피너를 표시해요(값이 true면 기본값 사용); 뒤에서 무언가 일어나고 있음을 전달하는 데 유용해요; 팁: persistent, ok: false 및 update() 메서드와 함께 사용하세요 객체 형태:spinner(Component, optional) QSpinners 중 하나color(string, optional) Quasar 색상 팔레트의 컴포넌트 색상 이름 예시:'primary','teal','teal-10'
ok(string | object | boolean, optional) 'OK' 버튼의 props 객체 형태:...props(any, optional) 사용 가능한 props는 QBtn 참고
cancel(string | object | boolean, optional) 'CANCEL' 버튼의 props 객체 형태:...props(any, optional) 사용 가능한 props는 QBtn 참고
focus(string, optional), 기본값'ok''prompt'나 'options'가 없을 때 포커스할 버튼 허용값:'ok','cancel','none'stackButtons(boolean, optional) 버튼을 세로 정렬 대신 쌓이게 해요color(string, optional) Quasar 색상 팔레트의 컴포넌트 색상 이름 예시:'primary','teal','teal-10'dark(boolean, optional), 기본값null다크 모드 적용persistent(boolean, optional) 사용자가 다이얼로그 밖을 클릭하거나 ESC 키를 눌러도 닫을 수 없어요; 또한 앱 라우트 변경으로도 닫히지 않아요noEscDismiss(boolean, optional) 사용자가 ESC 키로 다이얼로그를 닫을 수 없어요; 'persistent' prop이 설정되어 있으면 설정할 필요가 없어요noBackdropDismiss(boolean, optional) 사용자가 밖을 클릭해 다이얼로그를 닫을 수 없어요; 'persistent' prop이 설정되어 있으면 설정할 필요가 없어요noRouteDismiss(boolean, optional) 앱 라우트 변경이 다이얼로그를 닫지 않아요; 'persistent' prop이 설정되어 있으면 설정할 필요가 없어요seamless(boolean, optional) 다이얼로그를 seamless 모드로 전환해요; 배경을 사용하지 않아 사용자가 페이지의 나머지 부분과도 상호작용할 수 있어요maximized(boolean, optional) 다이얼로그를 최대화 모드로 전환해요fullWidth(boolean, optional) 다이얼로그가 창과 같은 너비로 렌더링하려고 해요fullHeight(boolean, optional) 다이얼로그가 창과 같은 높이로 렌더링하려고 해요transitionShow(string, optional), 기본값'scale'Quasar의 내장 전환 중 하나 예시:'fade','slide-down'transitionHide(string, optional), 기본값'scale'Quasar의 내장 전환 중 하나 예시:'fade','slide-down'component(Component | string, optional) 커스텀 다이얼로그 컴포넌트 사용; 가능하면 'componentProps' prop과 함께 사용하세요 예시:CustomComponent,'custom-component'componentProps(object, optional) 'component' prop이 사용되면 기본 커스텀 컴포넌트로 전달되는 사용자 정의 props; 'persistent'나 'seamless' 같은 내장 QDialog 옵션도 포함할 수 있어요 반환:object체인 가능한 객체 객체 형태:onOk(Function, required) OK를 누르거나/옵션을 선택했을 때 무엇을 할지 알려주는 Function 파라미터를 받아요 함수 시그니처:(callbackFn: Function) => object파라미터:callbackFn(Function, required) 무엇을 할지 알려줘요 함수 시그니처:(payload?: any) => void예시:() => console.log('OK!')payload => Notify.create({ type: 'positive', message:Successfully saved '${payload.book.name}' book!})파라미터:payload(any, optional) onDialogOK를 파라미터와 함께 호출하거나 'ok' 이벤트로 방출된 경우의 payload 예시:'Quasar Framework'[1, 2, 6, 3]{ book: { id: 1, name: 'Lorem Ipsum' }, user: { name: 'Lorem J. Ipsum', role: 'admin' } }반환:object체인된 객체
onCancel(Function, required) Cancel을 누르거나/다이얼로그가 닫힐 때 무엇을 할지 알려주는 Function 파라미터를 받아요 함수 시그니처:(callbackFn: Function) => object파라미터:callbackFn(Function, required) 무엇을 할지 알려줘요 함수 시그니처:(reason?: string) => void예시:() => console.log('Cancelled'),reason => { if (reason === 'cancel') { console.log('Cancel button was clicked') } }파라미터:reason(string, optional) (v2.28 추가) 다이얼로그가 닫힌 이유: Cancel 버튼, 배경 클릭, ESC 키, 또는 코드를 통한 숨김(앱 라우트 변경 포함); 커스텀 컴포넌트에서는 컴포넌트의 'hide' 이벤트 payload를 반영해요 허용값:'cancel','backdrop','escape','programmatic'반환:object체인된 객체
onDismiss(Function, required) 다이얼로그가 닫힐 때 무엇을 할지 알려주는 Function 파라미터를 받아요 함수 시그니처:(callbackFn: Function) => object파라미터:callbackFn(Function, required) 무엇을 할지 알려줘요 함수 시그니처:(payload?: any) => void파라미터:payload(any, optional) (v2.28 추가) OK로 닫힌 경우 onOk 콜백이 받는 것과 같은 payload; 그렇지 않으면 닫힘 이유('cancel', 'backdrop', 'escape' 또는 'programmatic') 반환:object체인된 객체
hide(Function, required) 호출하면 다이얼로그를 숨겨요 함수 시그니처:() => object반환:object체인된 객체update(Function, required) 초기 속성(create() 파라미터로 주어진)을 'component'를 제외하고 업데이트해요 함수 시그니처:(opts: object) => object파라미터:opts(object, required) 'component' prop과 함께 사용하면 현재 'componentProps'를 업데이트할 props(이전 'componentProps' 위에 얕게 병합됨); 그렇지 않으면 이전 create() 파라미터 객체와 얕게 병합할 props 반환:object체인된 객체
Vue 주입 (Vue Injection)
$q.dialog을 통해 접근할 수 있어요(예: Options API에서는 this.$q.dialog, Composition API에서는 useQuasar().dialog).
설치 (Installation)
quasar.config.js에 추가해요:
framework: {
plugins: [
'Dialog'
]
}
내장 컴포넌트 (Built-in component)
예시 "Vue 파일 밖에서":
import { Dialog } from 'quasar'
(Object) Dialog.create({ ... })
// inside of a Vue file
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.dialog({ ... }) // returns Object
}
API 카드에서 반환된 Object가 무엇인지 확인하세요.
사용법 (Usage)
[!TIP] 아래의 모든 예시에서, 확인하면서 브라우저 콘솔도 함께 보세요.
[!NOTE] 이것은 Quasar 플러그인으로 다이얼로그로 할 수 있는 일의 완전한 목록이 아니에요. 더 탐구하려면 API 섹션을 확인하세요.
예시 "기본 (Basic)":
<template>
<div class="q-gutter-sm">
<q-btn label="Alert" color="primary" @click="alert" />
<q-btn label="Confirm" color="primary" @click="confirm" />
<q-btn label="Prompt" color="primary" @click="prompt" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function alert() {
$q.dialog({
title: 'Alert',
message: 'Some message'
})
.onOk(() => {
console.log('OK')
})
.onCancel(() => {
console.log('Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function confirm() {
$q.dialog({
title: 'Confirm',
message: 'Would you like to turn on the wifi?',
cancel: true,
persistent: true
})
.onOk(() => {
console.log('>>>> OK')
})
.onOk(() => {
console.log('>>>> second OK catcher')
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function prompt() {
$q.dialog({
title: 'Prompt',
message: 'What is your name?',
prompt: {
model: '',
type: 'text' // optional
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
</script>
예시 "다크 모드 강제 (Force dark mode)":
<template>
<div class="q-gutter-sm">
<q-btn label="Alert" color="primary" @click="alert" />
<q-btn label="Confirm" color="primary" @click="confirm" />
<q-btn label="Prompt" color="primary" @click="prompt" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function alert() {
$q.dialog({
dark: true,
title: 'Alert',
message: 'Some message'
})
.onOk(() => {
console.log('OK')
})
.onCancel(() => {
console.log('Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function confirm() {
$q.dialog({
dark: true,
title: 'Confirm',
message: 'Would you like to turn on the wifi?',
cancel: true,
persistent: true
})
.onOk(() => {
console.log('>>>> OK')
})
.onOk(() => {
console.log('>>>> second OK catcher')
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function prompt() {
$q.dialog({
dark: true,
title: 'Prompt',
message: 'What is your name?',
prompt: {
model: '',
type: 'text' // optional
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
</script>
예시 "라디오, 체크박스, 토글 (Radios, Checkboxes, Toggles)":
<template>
<div class="q-gutter-sm">
<q-btn label="Radio Options" color="primary" @click="radio" />
<q-btn label="Checkbox Options" color="primary" @click="checkbox" />
<q-btn label="Toggle Options" color="primary" @click="toggle" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function radio() {
$q.dialog({
title: 'Options',
message: 'Choose an option:',
options: {
type: 'radio',
model: 'opt1',
// inline: true
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function checkbox() {
$q.dialog({
title: 'Options',
message: 'Choose your options:',
options: {
type: 'checkbox',
model: [],
// inline: true
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function toggle() {
$q.dialog({
title: 'Options',
message: 'Choose your options:',
options: {
type: 'toggle',
model: [],
// inline: true,
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
</script>
예시 "다른 옵션들 (Other options)":
<template>
<div class="q-gutter-sm">
<q-btn label="Custom Buttons" color="primary" @click="customBtn" />
<q-btn label="Positioned" color="primary" @click="positioned" />
<q-btn label="Stacked Buttons" color="primary" @click="stacked" />
<q-btn label="Auto Closing" color="primary" @click="autoClose" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function customBtn() {
$q.dialog({
title: 'Confirm',
message: 'Would you like to turn on the wifi?',
ok: {
push: true
},
cancel: {
push: true,
color: 'negative'
},
persistent: true
})
.onOk(() => {
console.log('>>>> OK')
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
function positioned() {
$q.dialog({
title: 'Positioned',
message: 'This dialog appears from bottom.',
position: 'bottom'
})
}
function stacked() {
$q.dialog({
title: 'Stacked Buttons',
stackButtons: true,
cancel: true
})
}
function autoClose() {
let seconds = 3
const dialog = $q
.dialog({
title: 'Alert',
message: `Autoclosing in ${seconds} seconds.`
})
.onOk(() => {
console.log('OK')
})
.onCancel(() => {
console.log('Cancel')
})
.onDismiss(() => {
clearTimeout(timer)
console.log('I am triggered on both OK and Cancel')
})
const timer = setInterval(() => {
seconds--
if (seconds > 0) {
dialog.update({
message: `Autoclosing in ${seconds} second${seconds > 1 ? 's' : ''}.`
})
} else {
clearInterval(timer)
dialog.hide()
}
}, 1000)
}
</script>
닫힘 이유 (Dismissal reason) (v2.28+)
onCancel 콜백은 닫힘 이유를 받아요: cancel(Cancel 버튼), backdrop, escape(ESC 키), programmatic(코드를 통한 숨김, 앱 라우트 변경 포함).
onDismiss 콜백도 같은 이유를 받지만, 다이얼로그가 OK로 닫힌 경우에는 onOk 콜백이 받는 payload를 받아요.
커스텀 컴포넌트를 호출할 때(아래 섹션 참고), 이유는 여러분 컴포넌트의 hide 이벤트 payload를 반영해요: useDialogPluginComponent 컴포저블은 위 값을 여러분을 위해 방출하는 반면, 직접 작성한 컴포넌트는 자체 payload(또는 없음)를 결정해요.
예시 "닫힘 이유":
<template>
<div class="q-gutter-sm">
<q-btn label="Open dialog" color="primary" @click="show" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function show() {
$q.dialog({
title: 'Confirm',
message:
'Dismiss this dialog through the Cancel button, the backdrop or the ESC key.',
cancel: true
})
.onOk(() => {
console.log('OK')
})
.onCancel(reason => {
// reason is 'cancel', 'backdrop', 'escape' or 'programmatic'
console.log(`Dismissed through: ${reason}`)
})
}
</script>
네이티브 속성 (Native attributes)
아래 예시처럼 내부 QInput이나 QOptionGroup 컴포넌트에 네이티브 HTML 속성을 제공할 수도 있어요.
예시 "네이티브 속성 사용":
<template>
<div class="q-gutter-sm">
<q-btn label="Prompt (1-10, step 2)" color="primary" @click="prompt" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function prompt() {
$q.dialog({
title: 'Prompt with native attributes',
message: 'Please type a value between 0 and 10:',
prompt: {
model: 2,
type: 'number',
// native attributes:
min: 0,
max: 10,
step: 2
},
cancel: true,
persistent: true
})
.onOk(data => {
console.log('>>>> OK, received', data)
})
.onCancel(() => {
console.log('>>>> Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
</script>
사용자 입력 검증 (User input validation)
사용자가 기대하는 값이 채워질 때까지 다이얼로그를 제출할 수 없게("OK"를 클릭/탭하거나 Enter를 누르는) 하는 기본 검증 시스템이 있어요.
예시 "검증이 있는 프롬프트":
<template>
<q-btn label="Prompt" color="primary" @click="prompt" />
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function prompt() {
$q.dialog({
title: 'Prompt',
message: 'What is your name? (Minimum 3 characters)',
prompt: {
model: '',
isValid: val => val.length > 2, // << here is the magic
type: 'text' // optional
},
cancel: true,
persistent: true
}).onOk(data => {
console.log('>>>> OK, received', data)
})
}
</script>
예시 "검증이 있는 옵션":
<template>
<div class="q-gutter-sm">
<q-btn label="Radio Options" color="primary" @click="radio" />
<q-btn label="Checkbox Options" color="primary" @click="checkbox" />
<q-btn label="Toggle Options" color="primary" @click="toggle" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function radio() {
$q.dialog({
title: 'Options',
message: "Choose your option, but make sure it's the second one :)",
options: {
type: 'radio',
model: 'opt1',
isValid: val => val === 'opt2',
// inline: true
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
}).onOk(data => {
console.log('>>>> OK, received', data)
})
}
function checkbox() {
$q.dialog({
title: 'Options',
message: 'Choose your options, but make sure you also pick the second one.',
options: {
type: 'checkbox',
model: [],
isValid: model => model.includes('opt2'),
// inline: true
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
}).onOk(data => {
console.log('>>>> OK, received', data)
})
}
function toggle() {
$q.dialog({
title: 'Options',
message: 'Choose your options, but make sure you also pick the first two.',
options: {
type: 'toggle',
model: [],
isValid: model => model.includes('opt1') && model.includes('opt2'),
// inline: true,
items: [
{ label: 'Option 1', value: 'opt1', color: 'secondary' },
{ label: 'Option 2', value: 'opt2' },
{ label: 'Option 3', value: 'opt3' }
]
},
cancel: true,
persistent: true
}).onOk(data => {
console.log('>>>> OK, received', data)
})
}
</script>
진행 상황 (Progress)
예시 "진행 상황 표시":
<template>
<div class="q-gutter-sm">
<q-btn label="Default progress" color="primary" @click="showDefault" />
<q-btn label="Custom progress" color="primary" @click="showCustom" />
</div>
</template>
<script setup>
import { QSpinnerGears, useQuasar } from 'quasar'
const $q = useQuasar()
function showDefault() {
const dialog = $q.dialog({
message: 'Uploading... 0%',
progress: true, // we enable default settings
persistent: true, // we want the user to not be able to close it
ok: false // we want the user to not be able to close it
})
// 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
dialog.update({
message: `Uploading... ${percentage}%`
})
// if we are done, we're gonna close it
if (percentage === 100) {
clearInterval(interval)
setTimeout(() => {
dialog.hide()
}, 350)
}
}, 500)
}
function showCustom() {
const dialog = $q.dialog({
title: 'Uploading...',
dark: true,
message: '0%',
progress: {
spinner: QSpinnerGears,
color: 'amber'
},
persistent: true, // we want the user to not be able to close it
ok: false // we want the user to not be able to close it
})
// 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
dialog.update({
message: `${percentage}%`
})
// if we are done...
if (percentage === 100) {
clearInterval(interval)
dialog.update({
title: 'Done!',
message: 'Upload completed successfully',
progress: false,
ok: true
})
}
}, 500)
}
</script>
HTML 사용 (Using HTML)
html: true prop을 지정하면 title과 message에 HTML을 사용할 수 있어요. 이것은 XSS 공격으로 이어질 수 있으므로, 메시지를 직접 소독해야 한다는 점을 유의하세요.
예시 "안전하지 않은 HTML 메시지":
<template>
<div class="q-gutter-sm">
<q-btn label="Show HTML Dialog" color="primary" @click="showDialog" />
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
function showDialog() {
$q.dialog({
title: 'Alert<em>!</em>',
message:
'<em>I can</em> <span class="text-red">use</span> <strong>HTML</strong>',
html: true
})
.onOk(() => {
console.log('OK')
})
.onCancel(() => {
console.log('Cancel')
})
.onDismiss(() => {
console.log('I am triggered on both OK and Cancel')
})
}
</script>
커스텀 컴포넌트 호출 (Invoking custom component)
Dialog 플러그인이 기본 제공하는 기본 컴포넌트에 의존하기보다 자체 커스텀 컴포넌트를 호출할 수도 있어요. 하지만 이 경우 모든 것(자체 컴포넌트 props 포함)을 처리할 책임이 있어요.
이 기능은 사실 Dialog 플러그인의 "핵심"이에요. 다이얼로그 기능을 분리하고 쉽게 재사용함으로써 다른 vue 컴포넌트의 html 템플릿을 깔끔하게 유지하는 데 도움이 돼요.
커스텀 컴포넌트 트리거 (Triggering the custom component)
예시 "Dialog import로":
/**
* This way of using it can reside outside
* of a Vue component as well
*/
import { Dialog } from 'quasar'
import CustomComponent from '..path.to.component..'
Dialog.create({
component: CustomComponent,
// props forwarded to your custom component
componentProps: {
text: 'something',
persistent: true,
// ...more..props...
}
}).onOk(() => {
console.log('OK')
}).onCancel(reason => {
// reason (Quasar v2.28+) is 'cancel', 'backdrop',
// 'escape' or 'programmatic'
console.log('Cancel', reason)
}).onDismiss(() => {
console.log('Called on OK or Cancel')
})
예시 "useQuasar() 사용":
/**
* This way of using it can reside ONLY
* inside of a Vue component
*/
import { useQuasar } from 'quasar'
import CustomComponent from '..path.to.component..'
setup () {
const $q = useQuasar()
$q.dialog({
component: CustomComponent,
// props forwarded to your custom component
componentProps: {
text: 'something',
persistent: true,
// ...more..props...
}
}).onOk(() => {
console.log('OK')
}).onCancel(reason => {
// reason (Quasar v2.28+) is 'cancel', 'backdrop',
// 'escape' or 'programmatic'
console.log('Cancel', reason)
}).onDismiss(() => {
console.log('Called on OK or Cancel')
})
}
위와 동일한 것을 Options API로 하려면 직접 this.$q.dialog({ ... })을 사용하면 돼요.
[!IMPORTANT] 여러분의 커스텀 컴포넌트는 Dialog 플러그인에 완벽하게 연결되려면 아래에 설명된 인터페이스를 따라야 해요. "REQUIRED" 주석에 주의하고 있는 그대로 받아들이세요 — 그냥 뼈대 예시일 뿐, 그 이상도 아니에요.
커스텀 컴포넌트 작성 (Writing the custom component)
"script setup" 및 Composition API 변형의 SFC
useDialogPluginComponent 컴포저블을 사용할 거예요.
<template>
<q-dialog ref="dialogRef" @hide="onDialogHide">
<q-card class="q-dialog-plugin">
<!--
...content
... use q-card-section for it?
-->
<!-- buttons example -->
<q-card-actions align="right">
<q-btn color="primary" label="OK" @click="onOKClick" />
<q-btn color="primary" label="Cancel" @click="onDialogCancel" />
</q-card-actions>
</q-card>
</q-dialog>
</template>
<script setup>
import { useDialogPluginComponent } from 'quasar'
const props = defineProps({
// ...your custom props
})
defineEmits([
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emits
])
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
useDialogPluginComponent()
// dialogRef - Vue ref to be applied to QDialog
// onDialogHide - Function to be used as handler for @hide on QDialog;
// bind it directly (no wrapping) so it receives QDialog's
// event and can forward the dismissal reason to the
// chained onCancel/onDismiss callbacks (Quasar v2.28+)
// onDialogOK - Function to call to settle dialog with "ok" outcome
// example: onDialogOK() - no payload
// example: onDialogOK({ /*...*/ }) - with payload
// onDialogCancel - Function to call to settle dialog with "cancel" outcome
// this is part of our example (so not required)
function onOKClick() {
// on OK, it is REQUIRED to
// call onDialogOK (with optional payload)
onDialogOK()
// or with payload: onDialogOK({ ... })
// ...and it will also hide the dialog automatically
}
</script>
emits를 Object 형태로 정의하고 싶다면:
defineEmits({
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emitsObject
// ...your own definitions
})
예시: 비동기 제출 (Example: async submission)
내장 다이얼로그는 OK 버튼을 클릭하는 즉시 정착돼요. 제출이 비동기 작업(예: 서버에 저장)을 기다려야 할 때는 커스텀 컴포넌트를 호출하세요: onDialogOK()을 바로 호출하도록 강제하는 것은 없으므로, 제출 버튼을 로딩 상태로 둔 채 다이얼로그를 열어 두고, 작업이 성공할 때만 정착시키며 실패하면 오류를 표시하면서 열어 둘 수 있어요.
아래의 :persistent="submitting"에 주목하세요. 작업이 진행 중인 동안 사용자가 다이얼로그를(배경 클릭이나 ESC로) 닫지 못하게 해요.
<template>
<q-dialog ref="dialogRef" :persistent="submitting" @hide="onDialogHide">
<q-card class="q-dialog-plugin">
<q-card-section>
<q-input
v-model="name"
label="Name"
:disable="submitting"
:error="error !== null"
:error-message="error"
/>
</q-card-section>
<q-card-actions align="right">
<q-btn
flat
color="primary"
label="Cancel"
:disable="submitting"
@click="onDialogCancel"
/>
<q-btn
color="primary"
label="Save"
:loading="submitting"
@click="onSaveClick"
/>
</q-card-actions>
</q-card>
</q-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { useDialogPluginComponent } from 'quasar'
defineEmits([
// REQUIRED; need to specify some events that your
// component will emit through useDialogPluginComponent()
...useDialogPluginComponent.emits
])
const { dialogRef, onDialogHide, onDialogOK, onDialogCancel } =
useDialogPluginComponent()
const name = ref('')
const submitting = ref(false)
const error = ref(null)
async function onSaveClick() {
submitting.value = true
error.value = null
try {
// replace with your own async operation (fetch/axios/etc)
const result = await api.save({ name: name.value })
// settle the dialog with an "ok" outcome only now;
// the payload reaches the chained onOk() callbacks
// and the dialog hides automatically
onDialogOK(result)
} catch (err) {
// the dialog stays open; display the error
error.value = err.message
} finally {
submitting.value = false
}
}
</script>
호출하는 쪽은 어떤 식으로도 변경되지 않아요:
$q.dialog({
component: SaveDialog
}).onOk(result => {
// the payload passed to onDialogOK() above
console.log('saved', result)
})
Cordova/Capacitor 뒤로 가기 버튼 (Cordova/Capacitor back button)
Quasar는 기본적으로 뒤로 가기 버튼을 처리해서, 닫힌 다이얼로그를 이전 페이지로 돌아가는 기본 동작(좋은 사용자 경험이 아님) 대신 숨길 수 있게 해줘요.
하지만 이 동작을 비활성화하고 싶다면 /quasar.config 파일을 편집하세요:
예시 "Capacitor용":
// quasar.config file
return {
framework: {
config: {
capacitor: {
// Quasar handles app exit on mobile phone back button.
backButtonExit: true/false/'*'/['/login', '/home', '/my-page'],
// On the other hand, the following completely
// disables Quasar's back button management.
backButton: true/false
}
}
}
}
예시 "Cordova용":
// quasar.config file
return {
framework: {
config: {
cordova: {
// Quasar handles app exit on mobile phone back button.
backButtonExit: true/false/'*'/['/login', '/home', '/my-page'],
// On the other hand, the following completely
// disables Quasar's back button management.
backButton: true/false
}
}
}
}
더 알아보기 (Learn more)
Dialog 플러그인은 $q.dialog({...})으로 프로그래밍 방식으로 세 가지 유형(프롬프트, 옵션 선택, 확인)의 다이얼로그를 만들 수 있게 해요. prompt/options로 입력 폼과 선택 폼을, position/dark/progress/persistent 등을 커스터마이즈하고, 반환 객체의 체인(onOk/onCancel/onDismiss/hide/update)으로 동작을 처리해요. v2.28+부터 onCancel/onDismiss가 닫힘 이유를 받고, component/componentProps로 커스텀 컴포넌트를 렌더링할 수 있어요(useDialogPluginComponent 컴포저블 사용). Cordova/Capacitor에서는 뒤로 가기 버튼이 열린 다이얼로그를 숨기도록 기본 처리돼요.