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
}