Modal 對話框
在頁面上方彈出一個帶遮罩的視窗,用來確認操作、展示詳情或填寫一小段表單,不離開目前頁面。只是確認一句話時用 Popconfirm 更輕;內容較多、需要從螢幕一側滑出時用 Drawer。
引入
import { HuiModal } from '@nscode/handy-ui'
基礎用法
用 v-model:visible 控制顯示,title 是標題,內容放在預設插槽裡。點右上角的 ×、點對話框外面或按 Esc 都可以關閉。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton } from '@nscode/handy-ui'
const visible = ref(false)
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開對話框</HuiButton>
<HuiModal v-model:visible="visible" title="提示">
<p>這是對話框的內容。</p>
</HuiModal>
</template>
底部按鈕
操作按鈕放在 footer 插槽裡,靠右排列。沒有寫 footer 插槽且未開啟 show-footer 時不顯示底部區域。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiMessage } from '@nscode/handy-ui'
const visible = ref(false)
const submit = () => {
visible.value = false
HuiMessage.success('已提交')
}
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開對話框</HuiButton>
<HuiModal v-model:visible="visible" title="確認操作" width="420px">
<p>確定要提交這份表單嗎?</p>
<template #footer>
<HuiButton @click="visible = false">取消</HuiButton>
<HuiButton type="primary" @click="submit">確定</HuiButton>
</template>
</HuiModal>
</template>
內建頁腳
設定 show-footer 顯示內建的取消、確定按鈕,預設文字隨語言包切換。before-confirm 返回 false 或拒絕時保留彈窗;回傳 Promise 時確定按鈕自動載入,期間取消、關閉按鈕、遮罩和 Esc 都不響應。確定通過後依次發 confirm、update:visible(false) 和 close('confirm')。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiMessage } from '@nscode/handy-ui'
const visible = ref(false)
const save = async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 1000))
return true
}
</script>
<template>
<HuiButton type="primary" @click="visible = true">儲存資料</HuiButton>
<HuiModal
v-model:visible="visible"
title="儲存資料"
width="420px"
show-footer
:before-confirm="save"
@confirm="HuiMessage.success('儲存成功')"
@cancel="HuiMessage.info('已取消儲存')"
>
<p>確定後等待一秒完成儲存。</p>
</HuiModal>
</template>
配置內建按鈕
文字屬性優先於語言包,空字串也會覆蓋預設文字。confirm-button-type 使用按鈕類型;兩個按鈕可以獨立隱藏。受控的 confirm-button-loading 只阻止確定,取消仍可操作。
確定按鈕獲得焦點後進入受控載入時,焦點暫時留在面板,載入結束後回到原按鈕;使用者主動把焦點移到其他可用控制項時保持使用者選擇。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiCheckbox, HuiSelect, HuiSpace } from '@nscode/handy-ui'
import type { ButtonType } from '@nscode/handy-ui'
const visible = ref(false)
const showConfirm = ref(true)
const showCancel = ref(true)
const loading = ref(false)
const type = ref<ButtonType>('primary')
const options = ['primary', 'success', 'warning', 'danger', 'info', 'help', 'default'].map(
(value) => ({ label: value, value })
)
</script>
<template>
<HuiSpace wrap align="center">
<HuiSelect v-model="type" :options="options" style="width: 140px" />
<HuiCheckbox v-model="showConfirm">顯示確定</HuiCheckbox>
<HuiCheckbox v-model="showCancel">顯示取消</HuiCheckbox>
<HuiCheckbox v-model="loading">受控載入</HuiCheckbox>
<HuiButton @click="visible = true">打開配置示例</HuiButton>
</HuiSpace>
<HuiModal
v-model:visible="visible"
title="按鈕配置"
width="420px"
show-footer
confirm-button-text="儲存"
cancel-button-text="返回"
:confirm-button-type="type"
:show-confirm-button="showConfirm"
:show-cancel-button="showCancel"
:confirm-button-loading="loading"
>
<p>按鈕狀態由頁面上的配置決定。</p>
</HuiModal>
</template>
頁腳作用域
footer 插槽覆蓋內建按鈕,提供 confirm、cancel、confirmLoading。自訂按鈕呼叫它們時也會經過驗證和等待保護,show-footer 可以省略。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiMessage } from '@nscode/handy-ui'
const visible = ref(false)
const save = async () => {
await new Promise<void>((resolve) => setTimeout(resolve, 1000))
}
</script>
<template>
<HuiButton @click="visible = true">自訂頁腳</HuiButton>
<HuiModal
v-model:visible="visible"
title="自訂操作"
width="420px"
:before-confirm="save"
@confirm="HuiMessage.success('已儲存')"
>
<p>自訂按鈕沿用同一套確定和取消流程。</p>
<template #footer="{ confirm, cancel, confirmLoading }">
<HuiButton :disabled="confirmLoading" @click="cancel">返回</HuiButton>
<HuiButton type="success" :loading="confirmLoading" @click="confirm">儲存</HuiButton>
</template>
</HuiModal>
</template>
關閉原因
before-close(trigger) 區分取消、關閉按鈕、遮罩和 Esc。下面點取消直接關閉,其他入口先詢問;回傳的 Promise 等待期間所有關閉入口鎖定。外部直接改 v-model:visible 關閉時不呼叫驗證,close 事件沒有原因參數。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { ModalCloseTrigger } from '@nscode/handy-ui'
const visible = ref(false)
const last = ref('尚未關閉')
const beforeClose = async (trigger: ModalCloseTrigger) => {
if (trigger === 'cancel') return true
try {
await HuiMessageBox.confirm('資料尚未儲存,確定關閉嗎?', '關閉資料')
return true
} catch {
return false
}
}
const onClose = (trigger?: ModalCloseTrigger | 'confirm') => {
last.value = trigger ?? '外部修改 v-model:visible'
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="visible = true">查看關閉原因</HuiButton>
<span>最近關閉:{{ last }}</span>
</HuiSpace>
<HuiModal
v-model:visible="visible"
title="關閉原因"
width="420px"
show-footer
:before-close="beforeClose"
@close="onClose"
>
<p>可以分別點擊取消、關閉按鈕、遮罩,或按 Esc。</p>
</HuiModal>
</template>
寬度
width 預設 50%,可以傳數字(按 px 處理)或帶單位的字串。視口比較窄時,對話框最寬占視口的 90%。點下面的按鈕看不同寬度:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
const width = ref<string | number>('50%')
const open = (value: string | number) => {
width.value = value
visible.value = true
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('30%')">30%</HuiButton>
<HuiButton @click="open('50%')">50%(預設)</HuiButton>
<HuiButton @click="open('80%')">80%</HuiButton>
<HuiButton @click="open(360)">數字 360(按 px)</HuiButton>
<HuiButton @click="open('600px')">600px</HuiButton>
</HuiSpace>
<HuiModal v-model:visible="visible" :title="`width:${width}`" :width="width">
<p>對話框的寬度由 width 決定,窄屏下最寬占視口的 90%。</p>
</HuiModal>
</template>
位置
top 是對話框離視口頂部的距離,預設 15vh,同樣可以傳數字(按 px 處理)或帶單位的字串。center 讓對話框在視口裡垂直居中,這時 top 不起作用。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
const top = ref<string | number>('15vh')
const center = ref(false)
const open = (value: string | number, isCenter = false) => {
top.value = value
center.value = isCenter
visible.value = true
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('15vh')">離頂部 15vh(預設)</HuiButton>
<HuiButton @click="open(40)">離頂部 40(按 px)</HuiButton>
<HuiButton @click="open('30vh')">離頂部 30vh</HuiButton>
<HuiButton @click="open('15vh', true)">垂直居中(center)</HuiButton>
</HuiSpace>
<HuiModal
v-model:visible="visible"
:title="center ? '垂直居中(center)' : `top:${top}`"
width="420px"
:top="top"
:center="center"
>
<p>對話框的內容。</p>
</HuiModal>
</template>
全螢幕
fullscreen 讓對話框占滿整個視口,width、top、center 都不起作用。內容多了在內容區裡捲動,頭部和底部固定。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton } from '@nscode/handy-ui'
const visible = ref(false)
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開全螢幕對話框</HuiButton>
<HuiModal v-model:visible="visible" title="全螢幕對話框" fullscreen>
<p v-for="i in 30" :key="i">第 {{ i }} 行內容</p>
<template #footer>
<HuiButton type="primary" @click="visible = false">關閉</HuiButton>
</template>
</HuiModal>
</template>
拖曳標題欄
加上 draggable 後,按住標題欄可以拖曳對話框,標題欄上的游標是移動的樣子,拖曳時不會選中文字。
標題欄移動達到 3px 才捕獲指標;僅按下並放開時不捕獲,插槽中的幫助圖示仍能收到點擊。
- 拖不出視口:對話框放得下時整個留在視口裡,拖到邊上就停住;比視口還高時,至少標題欄留在視口裡,隨時能拖回來。
- 按在右上角的關閉按鈕上不會開始拖曳,點擊照常關閉;
header插槽裡的按鈕、連結、輸入框也一樣。 - 全螢幕(
fullscreen)時不能拖,退出全螢幕後回到拖曳後的位置。 - 關閉後再打開,回到原來的位置。
下面第一個按鈕打開普通的可拖曳對話框,第二個打開比視口還高的,可以在底部切換全螢幕:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace, HuiIcon, HuiMessage } from '@nscode/handy-ui'
const visible = ref(false)
const tall = ref(false)
const fullscreen = ref(false)
const showHelp = () => HuiMessage.info('拖曳標題欄移動;拖曳時按 Esc 恢復原位置。')
const openTall = () => {
fullscreen.value = false
tall.value = true
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="primary" @click="visible = true">打開可拖曳的對話框</HuiButton>
<HuiButton @click="openTall">打開很高的對話框</HuiButton>
</HuiSpace>
<HuiModal v-model:visible="visible" title="按住標題欄拖曳" width="420px" draggable>
<template #header>
<HuiSpace
><span>按住標題欄拖曳</span
><HuiIcon
name="help"
role="button"
tabindex="0"
aria-label="拖曳幫助"
style="cursor: pointer"
@click="showHelp"
@keydown.enter.prevent="showHelp"
@keydown.space.prevent="showHelp"
/></HuiSpace>
</template>
<p>拖到視口邊上會停住,不會拖出去。</p>
<p>關掉再打開,對話框回到原來的位置。</p>
<template #footer>
<HuiButton type="primary" @click="visible = false">知道了</HuiButton>
</template>
</HuiModal>
<HuiModal
v-model:visible="tall"
title="很高的對話框"
width="480px"
draggable
:fullscreen="fullscreen"
>
<p v-for="i in 40" :key="i">第 {{ i }} 行內容</p>
<template #footer>
<HuiButton @click="fullscreen = !fullscreen">
{{ fullscreen ? '退出全螢幕(可以拖)' : '全螢幕(不能拖)' }}
</HuiButton>
<HuiButton type="primary" @click="tall = false">關閉</HuiButton>
</template>
</HuiModal>
</template>
限制關閉方式
三個開關分別控制三種關閉方式,預設都是開的:
close-on-click-modal:點對話框外面(遮罩)關閉。close-on-press-escape:按 Esc 關閉。show-close:顯示右上角的關閉按鈕。
三個都關掉以後,只能由你自己把 v-model:visible 的值改成 false 來關閉。下面每個按鈕關掉其中一種,最後一個三種都關掉:
<script setup lang="ts">
import { reactive, ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
const title = ref('')
const options = reactive({
closeOnClickModal: true,
closeOnPressEscape: true,
showClose: true
})
const open = (label: string, next: Partial<typeof options>) => {
Object.assign(options, { closeOnClickModal: true, closeOnPressEscape: true, showClose: true })
Object.assign(options, next)
title.value = label
visible.value = true
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('按遮罩不關閉', { closeOnClickModal: false })">
點遮罩不關閉(close-on-click-modal)
</HuiButton>
<HuiButton @click="open('按 Esc 不關閉', { closeOnPressEscape: false })">
按 Esc 不關閉(close-on-press-escape)
</HuiButton>
<HuiButton @click="open('沒有關閉按鈕', { showClose: false })">
不顯示關閉按鈕(show-close)
</HuiButton>
<HuiButton
type="primary"
@click="
open('只能按下方按鈕關閉', {
closeOnClickModal: false,
closeOnPressEscape: false,
showClose: false
})
"
>
三個都關掉
</HuiButton>
</HuiSpace>
<HuiModal
v-model:visible="visible"
:title="title"
width="420px"
:close-on-click-modal="options.closeOnClickModal"
:close-on-press-escape="options.closeOnPressEscape"
:show-close="options.showClose"
>
<p>點遮罩:{{ options.closeOnClickModal ? '關閉' : '不關閉' }}</p>
<p>按 Esc:{{ options.closeOnPressEscape ? '關閉' : '不關閉' }}</p>
<p>右上角的關閉按鈕:{{ options.showClose ? '顯示' : '不顯示' }}</p>
<template #footer>
<HuiButton type="primary" @click="visible = false">我知道了</HuiButton>
</template>
</HuiModal>
</template>
關閉前確認
傳了 before-close 以後,關閉入口先呼叫這個函式,返回 false、拋錯或拒絕時攔截,其餘回傳值(包括 undefined)放行。可以用來提示“還有內容沒儲存”,或者等一個非同步請求結束。
下面沒勾選“我已儲存”時,點 ×、點遮罩或按 Esc 會先彈出確認框;底部的按鈕直接改 v-model:visible,不經過 before-close。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiCheckbox, HuiMessageBox } from '@nscode/handy-ui'
const visible = ref(false)
const saved = ref(false)
const open = () => {
saved.value = false
visible.value = true
}
const beforeClose = async () => {
if (saved.value) return true
try {
await HuiMessageBox.confirm('還沒有儲存,確定要關閉嗎?', '提示', { type: 'warning' })
return true
} catch {
return false
}
}
</script>
<template>
<HuiButton type="primary" @click="open">編輯資料</HuiButton>
<HuiModal v-model:visible="visible" title="編輯資料" width="420px" :before-close="beforeClose">
<HuiCheckbox v-model="saved">我已儲存</HuiCheckbox>
<template #footer>
<HuiButton @click="visible = false">直接關閉</HuiButton>
</template>
</HuiModal>
</template>
自訂頭部
header 插槽替換標題,右上角的關閉按鈕還在。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiIcon, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開對話框</HuiButton>
<HuiModal v-model:visible="visible" width="460px">
<template #header>
<HuiSpace align="center">
<HuiIcon name="user" />
<strong>自訂頭部</strong>
<span class="subtitle">副標題</span>
</HuiSpace>
</template>
<p>內容</p>
</HuiModal>
</template>
<style scoped>
.subtitle {
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
關閉後保留或銷毀內容
對話框第一次打開時才呈現裡面的內容。預設關閉後只是隱藏,輸入框裡填的內容、捲動位置、子元件的狀態都還在;加上 destroy-on-close 後,關閉動畫結束時銷毀內容,下次打開重新呈現。
在兩個對話框的輸入框裡各輸入幾個字,關掉再打開對比:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const keep = ref(false)
const destroy = ref(false)
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="keep = true">預設:關閉後保留</HuiButton>
<HuiButton @click="destroy = true">destroy-on-close:關閉後銷毀</HuiButton>
</HuiSpace>
<HuiModal v-model:visible="keep" title="關閉後保留" width="420px">
<input class="demo-input" placeholder="輸入的內容再打開時還在" />
</HuiModal>
<HuiModal v-model:visible="destroy" title="關閉後銷毀" width="420px" destroy-on-close>
<input class="demo-input" placeholder="每次打開都是空的" />
</HuiModal>
</template>
<style scoped>
.demo-input {
box-sizing: border-box;
width: 100%;
height: var(--hui-component-size);
padding: 0 var(--hui-spacing-3);
color: var(--hui-text-color);
background: var(--hui-bg-color);
border: var(--hui-border-width) var(--hui-border-style) var(--hui-border-color);
border-radius: var(--hui-border-radius);
}
</style>
遮罩和頁面捲動
modal 設為 false 時不顯示遮罩,頁面可正常操作,點對話框外面不會關閉。lock-scroll 不寫時跟隨 modal,無模態時預設不鎖頁面捲動。
lock-scroll 不傳時跟隨 modal;顯式設為 false 後,打開對話框時仍然可以捲動頁面。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const noMask = ref(false)
const noLock = ref(false)
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="noMask = true">不顯示遮罩(modal=false)</HuiButton>
<HuiButton @click="noLock = true">不鎖定捲動(lock-scroll=false)</HuiButton>
</HuiSpace>
<HuiModal v-model:visible="noMask" title="沒有遮罩" :modal="false">
<p>沒有半透明遮罩,可直接操作頁面;點對話框外面不會關閉。</p>
</HuiModal>
<HuiModal v-model:visible="noLock" title="不鎖定頁面捲動" :lock-scroll="false">
<p>打開期間後面的頁面仍然可以捲動。</p>
</HuiModal>
</template>
多個對話框疊加
對話框裡可以再打開對話框。按 Esc 只關閉最後打開的那一個;頁面捲動要等所有對話框都關掉才恢復。
浮層按每次打開的先後分配層級:第一個使用最近ConfigProvider或應用配置的zIndex(預設2000),後打開的自動層級高於目前可見層;隱藏後重新整理自動層級,顯式zIndex保留。重開保留原根節點的位置和內部狀態,傳送的下拉、氣泡和固定批量欄按元件樹歸屬於父浮層。
裡面的下拉、氣泡和提示按層堆疊分配更高層級,關閉再打開對話框後仍顯示在父層上方。原位呈現的浮層(如 Popover teleport=false)仍受祖先的transform、filter、帶z-index定位元素及裁剪規則限制,不能跨越獨立層疊上下文。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton } from '@nscode/handy-ui'
const first = ref(false)
const second = ref(false)
</script>
<template>
<HuiButton type="primary" @click="first = true">打開第一層</HuiButton>
<HuiModal v-model:visible="first" title="第一層">
<HuiButton @click="second = true">打開第二層</HuiButton>
</HuiModal>
<HuiModal v-model:visible="second" title="第二層" width="360px" top="25vh">
<p>按 Esc 只關閉這一層。</p>
</HuiModal>
</template>
掛載目標
對話框預設掛到 body,不受元件祖先的 transform、filter、overflow 限制。需要放進指定容器時,append-to 可接收元素的選擇器或已連接到文件的 HTMLElement。每次打開和目標變化時重新解析;找不到、選擇器無效或元素已離開文件時,開發環境警告並改掛 body,關閉和卸載仍正常清理。初始就打開時,會等同一模板的節點掛載後再解析,因此目標可以寫在彈窗元件後面。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton } from '@nscode/handy-ui'
const visible = ref(false)
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開對話框</HuiButton>
<div
id="modal-mount-point"
style="min-height: 180px; border: 1px dashed var(--hui-border-color);"
>
指定的掛載容器
<HuiModal v-model:visible="visible" title="掛到指定容器" append-to="#modal-mount-point">
<p>關閉後內容仍由元件保留,重新打開繼續顯示。</p>
</HuiModal>
</div>
</template>
舊屬性 append-to-body 暫時保留一個版本:false 可繼續原位呈現,true 表示掛到 body。同時傳新舊屬性時 append-to 優先;遷移後請改用 append-to。
預設掛到 body 後,祖先選擇器、父元件 scoped 樣式中的 :deep()、祖先元素覆蓋的 CSS 變數和局部 data-palette 容器不再透過原 DOM 祖先作用於彈窗;原生 <form> 中的欄位掛走後也不再自動屬於原表單。需要暫時保留這些關係時,不傳 append-to 並使用 :append-to-body="false" 保持原位,或明確把彈窗掛入相應容器。Vue 的 provide、元件插槽和事件關係仍然保留。
事件
打開時依次觸發 open(開始打開)、opened(打開動畫結束);關閉時依次觸發 close(開始關閉)、closed(關閉動畫結束)。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiMessage } from '@nscode/handy-ui'
const visible = ref(false)
const onOpen = () => {
HuiMessage.info('open:開始打開')
}
const onOpened = () => {
HuiMessage.info('opened:打開動畫結束')
}
const onClose = () => {
HuiMessage.info('close:開始關閉')
}
const onClosed = () => {
HuiMessage.info('closed:關閉動畫結束')
}
</script>
<template>
<HuiButton type="primary" @click="visible = true">打開對話框</HuiButton>
<HuiModal
v-model:visible="visible"
title="事件"
@open="onOpen"
@opened="onOpened"
@close="onClose"
@closed="onClosed"
>
<p>內容</p>
</HuiModal>
</template>
無模態與非同步關閉判斷
無模態時可以操作頁面;before-close 返回 Promise<boolean> 決定關閉,顯式 lock-scroll 仍可覆蓋預設值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSwitch, HuiSpace } from '@nscode/handy-ui'
const visible = ref(false)
const allowed = ref(false)
const status = ref('')
const beforeClose = async () => allowed.value
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace align="center"
><HuiButton @click="visible = true">打開無模態對話框</HuiButton><span>允許關閉</span
><HuiSwitch v-model="allowed"
/></HuiSpace>
<p>{{ status }}</p>
<HuiModal
v-model:visible="visible"
title="可同時操作頁面"
:modal="false"
:before-close="beforeClose"
@open="status = 'open'"
@opened="status = 'opened'"
@closed="status = 'closed'"
>頁面上的“允許關閉”打開後可以關閉。</HuiModal
>
</HuiSpace>
</template>
用程式碼打開
HuiModal.open() 立即回傳控制代碼,預設帶內建頁腳。await handle.result 在關閉動畫結束且容器清理後回傳,確定、取消和其他關閉分別為 confirm、cancel、close,均不會 reject。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
const last = ref('尚未操作')
const open = async () => {
const handle = HuiModal.open({
title: '提交資料',
content: '資料準備就緒,可以提交。',
width: 420
})
const { action } = await handle.result
last.value = { confirm: '點了確定', cancel: '點了取消', close: '關閉了對話框' }[action]
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton type="primary" @click="open">用程式碼打開</HuiButton>
<span>{{ last }}</span>
</HuiSpace>
</template>
內容元件回傳資料
內容元件在 setup 裡呼叫 useModalContext(),用 onConfirm 註冊處理函式,回傳值作為結果資料。返回 false 或拒絕時保留彈窗,Promise 自動控制確定按鈕載入。內容元件的處理優先於 options.onConfirm,兩處都提供時開發環境會警告。
上下文只屬於這次函式呼叫的內容。內容裡再寫模板 HuiModal 或 HuiDrawer 時,內層內容的 useModalContext() 返回 undefined,不會覆蓋外層的確定處理;再次呼叫 HuiModal.open() 則得到新呼叫自己的上下文。
<script setup lang="ts">
import { defineComponent, h, ref } from 'vue'
import {
HuiModal,
HuiButton,
HuiCheckbox,
HuiMessage,
HuiSpace,
useModalContext
} from '@nscode/handy-ui'
interface Person {
id: number
name: string
}
const people: Person[] = [
{ id: 1, name: '张三' },
{ id: 2, name: '李四' },
{ id: 3, name: '王五' }
]
const selected = ref<Person[]>([])
const PeoplePicker = defineComponent({
setup() {
const ids = ref<number[]>([])
const modal = useModalContext<Person[]>()!
modal.onConfirm(() => {
if (!ids.value.length) {
HuiMessage.warning('請選擇至少一人')
return false
}
return people.filter((person) => ids.value.includes(person.id))
})
return () =>
h(HuiSpace, { direction: 'vertical' }, () =>
people.map((person) =>
h(
HuiCheckbox,
{
visible: ids.value.includes(person.id),
'onUpdate:visible': (checked: unknown) => {
ids.value = checked
? [...ids.value, person.id]
: ids.value.filter((id) => id !== person.id)
}
},
() => person.name
)
)
)
}
})
const open = async () => {
const result = await HuiModal.open<Person[]>({
title: '選擇人員',
component: PeoplePicker,
width: 420
}).result
if (result.action === 'confirm') selected.value = result.data ?? []
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="open">選擇人員</HuiButton>
<span>已選:{{ selected.map((person) => person.name).join('、') || '無' }}</span>
</HuiSpace>
</template>
內容自己提供按鈕
showFooter: false 隱藏內建頁腳,內容元件可以直接呼叫 modal.confirm(data)、modal.cancel() 或 modal.close()。這些方法直接結束,不經過 onConfirm 和 beforeClose。
<script setup lang="ts">
import { defineComponent, h, ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace, useModalContext } from '@nscode/handy-ui'
const last = ref('尚未選擇')
const Content = defineComponent({
setup() {
const modal = useModalContext<string>()!
return () =>
h(HuiSpace, { wrap: true }, () => [
h(
HuiButton,
{ type: 'primary', onClick: () => modal.confirm('已採用目前方案') },
() => '採用'
),
h(HuiButton, { onClick: modal.cancel }, () => '取消'),
h(HuiButton, { onClick: modal.close }, () => '關閉')
])
}
})
const open = async () => {
const result = await HuiModal.open<string>({
component: Content,
title: '選擇方案',
showFooter: false,
width: 420
}).result
last.value = result.action === 'confirm' ? (result.data ?? '') : result.action
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiButton @click="open">自訂內容按鈕</HuiButton>
<span>{{ last }}</span>
</HuiSpace>
</template>
更新和關閉控制代碼
handle.update() 更新尚未關閉的彈窗,handle.close() 直接關閉,HuiModal.closeAll() 關閉所有函式開啟的彈窗。兩種直接關閉都不經過 beforeClose,結果為 close。應用上下文在初次打開時確定。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiModal, HuiButton, HuiSpace } from '@nscode/handy-ui'
import type { ModalHandle } from '@nscode/handy-ui'
const handle = ref<ModalHandle>()
const last = ref('尚未操作')
const open = async () => {
const current = HuiModal.open({
title: '原標題',
content: () => '可以從頁面更新標題和寬度。',
modal: false,
width: 360
})
handle.value = current
const result = await current.result
last.value = result.action
if (handle.value?.id === current.id) handle.value = undefined
}
const update = () => handle.value?.update({ title: '更新後的標題', width: 520 })
const close = () => handle.value?.close()
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="open">打開無模態彈窗</HuiButton>
<HuiButton :disabled="!handle" @click="update">更新目前彈窗</HuiButton>
<HuiButton :disabled="!handle" @click="close">關閉目前彈窗</HuiButton>
<HuiButton @click="HuiModal.closeAll()">關閉全部函式彈窗</HuiButton>
</HuiSpace>
<span>最近結果:{{ last }}</span>
</HuiSpace>
</template>
傳送內容和關閉後的焦點
彈窗內傳送到 body 的下拉、氣泡仍屬於目前焦點範圍。可用 Tab 依次訪問;選單項打開函式開啟的彈窗後,選單收起,關閉彈窗會回到選單入口。
<script setup lang="ts">
import { h, ref } from 'vue'
import {
HuiButton,
HuiDropdown,
HuiDropdownItem,
HuiDropdownMenu,
HuiModal,
HuiPopover,
HuiSpace
} from '@nscode/handy-ui'
const visible = ref(false)
const edit = () =>
HuiModal.open({
title: '編輯名稱',
content: () => h('input', { 'aria-label': '名稱', autofocus: true })
})
</script>
<template>
<HuiSpace>
<HuiButton @click="visible = true">檢查傳送氣泡的 Tab 順序</HuiButton>
<HuiDropdown trigger="click" @command="edit">
<HuiButton>選單入口</HuiButton>
<template #dropdown
><HuiDropdownMenu
><HuiDropdownItem command="edit">編輯名稱</HuiDropdownItem></HuiDropdownMenu
></template
>
</HuiDropdown>
</HuiSpace>
<HuiModal v-model:visible="visible" title="焦點範圍">
<HuiSpace>
<HuiButton>框內按鈕</HuiButton>
<HuiPopover title="傳送到 body"
><HuiButton>打開氣泡</HuiButton
><template #content><HuiButton>氣泡內按鈕</HuiButton></template></HuiPopover
>
</HuiSpace>
</HuiModal>
</template>
Props
| 屬性 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| visible | boolean | false | 是否顯示,支援 v-model:visible |
| title | string | '' | 標題。也可以用 header 插槽 |
| width | string | number | '50%' | 對話框寬度,數字按 px 處理。最寬占視口的 90% |
| top | string | number | '15vh' | 對話框離視口頂部的距離,數字按 px 處理。center、fullscreen 時不起作用 |
| center | boolean | false | 是否在視口裡垂直居中 |
| fullscreen | boolean | false | 是否全螢幕 |
| modal | boolean | true | 是否顯示遮罩 |
| appendTo | string | HTMLElement | 'body' | 掛載目標;無效、缺失或離線時回退 body,每次打開重新解析 |
| appendToBody | boolean | - | 已廢棄,保留一個版本;false 原位呈現、true 掛到 body,新屬性優先 |
| lockScroll | boolean | modal 的值 | 不傳時有遮罩鎖頁面捲動、無模態時不鎖;顯式傳值優先 |
| closeOnClickModal | boolean | true | 點對話框外面是否關閉 |
| closeOnPressEscape | boolean | true | 按 Esc 是否關閉 |
| showClose | boolean | true | 是否顯示右上角的關閉按鈕 |
| beforeClose | (trigger: ModalCloseTrigger) => boolean | void | Promise<boolean | void> | - | 僅 false、拋錯或拒絕時攔截,其餘回傳值放行;Promise 等待期間鎖定其他入口 |
| showFooter | boolean | false | 沒有 footer 插槽時顯示內建頁腳 |
| confirmButtonText | string | 語言包“確定” | 內建確定按鈕文字,空串優先 |
| cancelButtonText | string | 語言包“取消” | 內建取消按鈕文字,空串優先 |
| confirmButtonType | ButtonType | 'primary' | 內建確定按鈕類型 |
| showConfirmButton | boolean | true | 是否顯示內建確定按鈕 |
| showCancelButton | boolean | true | 是否顯示內建取消按鈕 |
| confirmButtonLoading | boolean | false | 受控確定等待狀態,與 beforeConfirm 自動狀態取或 |
| beforeConfirm | () => boolean | void | Promise<boolean | void> | - | 確定前驗證,false 或拒絕保留;等待期間鎖定操作 |
| destroyOnClose | boolean | false | 關閉後是否銷毀裡面的內容 |
| draggable | boolean | false | 是否可以按住標題欄拖曳。拖不出視口,全螢幕時不能拖,關閉後再打開回到原位置 |
Events
| 事件 | 回呼參數 | 說明 |
|---|---|---|
| update:visible | (value: boolean) | 使用者關閉對話框或確定通過時觸發,值是 false |
| open | - | 開始打開時觸發,包括初始 visible 為 true 的掛載 |
| opened | - | 打開動畫結束時觸發 |
| close | (trigger?: ModalCloseTrigger | 'confirm') | 先更新 visible,再觸發 close;使用者操作帶原因,外部修改 v-model:visible 沒有參數,每輪只觸發一次 |
| closed | - | 關閉動畫結束時觸發 |
| confirm | - | 確定驗證通過後、關閉前觸發 |
| cancel | - | 點擊取消後、執行 beforeClose 前觸發;驗證拒絕也會觸發 |
Slots
| 插槽 | 作用域參數 | 說明 |
|---|---|---|
| default | - | 對話框的內容 |
| header | - | 頭部內容,替換 title。關閉按鈕不受影響 |
| footer | { confirm, cancel, confirmLoading } | 自訂操作區,覆蓋內建頁腳;函式沿用內建驗證與等待流程 |
方法
模板元件通過 v-model:visible 控制顯示;函式開啟的彈窗使用下面的靜態方法和控制代碼。
| 方法 | 參數 | 回傳值 | 說明 |
|---|---|---|---|
HuiModal.open<R>() | ModalOpenOptions<R> | ModalHandle<R> | 打開函式開啟的彈窗,預設內建頁腳開啟 |
HuiModal.closeAll() | - | void | 直接關閉所有函式開啟的彈窗 |
useModalContext<R>() | - | ModalContext<R> | undefined | 在內容元件的 setup 內獲取上下文,普通模板元件或元件外回傳 undefined |
handle.update() / modal.update() | Partial<ModalOpenOptions<R>> | void | 更新尚未關閉的彈窗,appContext 僅初次打開使用 |
handle.close() / modal.close() | - | void | 直接結束為 close |
modal.confirm() | data?: R | void | 直接確定並交回資料 |
modal.cancel() | - | void | 直接結束為 cancel |
modal.onConfirm() | () => R | false | void | Promise<R | false | void> | void | 註冊確定處理,setup 中登記時卸載自動撤銷 |
modal.setConfirmLoading() | boolean | void | 控制內建確定按鈕載入 |
ModalOpenOptions 支援下面的選項;同名外觀和行為參數沿用 Props 表。
| 選項 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| component | Component | - | 內容元件,優先於 content |
| props | Record<string, unknown> | - | 內容元件屬性 |
| content | string | VNode | (() => VNodeChild) | - | 文字、VNode 或呈現函式 |
| title / width / top | 同 Props | 同 Props | 標題、寬度、離頂部距離 |
| appendTo | string | HTMLElement | 'body' | 掛載到指定元素,關閉時僅清理彈層,不刪除目標 |
| center / fullscreen / draggable / modal | 同 Props | 同 Props | 版面配置和模態配置 |
| lockScroll / closeOnClickModal / closeOnPressEscape / showClose | 同 Props | 同 Props | 捲動與關閉行為 |
| showFooter | boolean | true | 與模板元件不同,函式呼叫預設帶頁腳 |
| confirmButtonText / cancelButtonText / confirmButtonType / showCancelButton | 同 Props | 同 Props | 內建按鈕配置 |
| onConfirm | () => R | false | void | Promise<R | false | void> | - | 回傳值作為 data;false 或拋錯/拒絕保留彈窗 |
| beforeClose | ModalProps['beforeClose'] | - | 使用者關閉前驗證;直接結束方法繞過它 |
| onOpened / onClosed | () => void | - | 進入和離開動畫結束回呼 |
| appContext | AppContext | null | 預設應用 | 繼承應用 provide、路由、store、全域元件 |
類型
import type {
ModalProps,
ModalEmits,
ModalCloseTrigger,
ModalFooterSlotProps,
ModalAction,
ModalResult,
ModalOpenOptions,
ModalHandle,
ModalContext
} from '@nscode/handy-ui'
type ModalCloseTrigger = 'close-button' | 'mask' | 'escape' | 'cancel'
interface ModalFooterSlotProps {
confirm: () => void
cancel: () => void
confirmLoading: boolean
}
type ModalAction = 'confirm' | 'cancel' | 'close'
interface ModalResult<R = unknown> {
action: ModalAction
data?: R
}
interface ModalHandle<R = unknown> {
readonly id: string
readonly result: Promise<ModalResult<R>>
close: () => void
update: (options: Partial<ModalOpenOptions<R>>) => void
}
interface ModalContext<R = unknown> {
readonly id: string
onConfirm: (handler: () => R | false | void | Promise<R | false | void>) => void
confirm: (data?: R) => void
cancel: () => void
close: () => void
setConfirmLoading: (loading: boolean) => void
update: (options: Partial<ModalOpenOptions<R>>) => void
}