Translation in progress
This page hasn't been translated into English yet, so the content below is in Chinese. The code examples work the same way.
MessageBox 消息弹框
模仿系统的 alert、confirm、prompt,在窗口中间弹出一个带遮罩的小对话框,用来提示、确认操作或让用户输入一项内容。用函数调用,返回 Promise。
引入
import { NsMessageBox } from '@ns/ui'
基础用法
NsMessageBox.alert(message, title) 弹出只有“确定”按钮的提示框。点确定时 Promise resolve;点右上角的关闭按钮、按 Esc 或点遮罩时 reject 'close',所以也要写 catch。
直接调用 NsMessageBox(message, title, options) 的默认效果和 alert 一样,只有确定按钮。
<script setup lang="ts">
import { NsButton, NsMessage, NsMessageBox, NsSpace } from '@ns/ui'
const open = () => {
NsMessageBox.alert('这是一条提示信息', '提示', { confirmButtonText: '知道了' })
.then(() => NsMessage.success('点了确定'))
.catch((action) => NsMessage.info(`关掉了:${action}`))
}
const openDirect = () => {
NsMessageBox('直接调用 NsMessageBox,默认只有确定按钮', '提示').catch(() => {})
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="open">显示提示框(alert)</NsButton>
<NsButton @click="openDirect">直接调用 NsMessageBox()</NsButton>
</NsSpace>
</template>
确认框
NsMessageBox.confirm 默认带“取消”按钮。点确定时 resolve;点取消时 reject 'cancel';点关闭按钮、按 Esc、点遮罩时 reject 'close',需要区分时看 reject 的值。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessageBox } from '@ns/ui'
const result = ref('')
const remove = async () => {
try {
await NsMessageBox.confirm('确定要删除这条记录吗?', '删除确认', {
confirmButtonText: '删除',
confirmButtonType: 'danger',
type: 'warning'
})
} catch (action) {
// action 是 'cancel' 或 'close'
result.value = `没有删除,reject 的值是 '${action}'`
return
}
result.value = '已删除'
}
</script>
<template>
<NsButton type="danger" @click="remove">删除</NsButton>
<p style="margin-top: 12px">{{ result || '点按钮,再分别点删除、取消、× 试试' }}</p>
</template>
输入框
NsMessageBox.prompt 在内容下面显示一个输入框,默认带“取消”按钮,占位文字默认是“请输入内容”。打开后焦点直接在输入框里,在输入框里按回车等同于点确定。点确定时 resolve 的 value 是输入的内容。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
const name = ref('')
const rename = async (placeholder?: string) => {
try {
const { value } = await NsMessageBox.prompt('请输入新的名称', '重命名', {
inputPlaceholder: placeholder
})
name.value = value ?? ''
} catch {
// 取消或关闭时不改名称
}
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="rename('不超过 20 个字')">重命名(自定义占位文字)</NsButton>
<NsButton @click="rename()">重命名(默认占位文字)</NsButton>
</NsSpace>
<p style="margin-top: 12px">当前名称:{{ name || '未命名' }}</p>
</template>
输入校验
点确定时按下面的顺序校验输入内容,不通过时在输入框下面显示错误,弹框不关闭:
inputPattern:正则不匹配时显示inputErrorMessage。inputValidator:返回false时显示inputErrorMessage;返回字符串时把这个字符串当错误提示;返回true表示通过。
inputErrorMessage 默认是“输入的数据不合法!”。
配置了 inputPlaceholder、inputPattern、inputValidator 中的任意一项,alert、confirm 也会显示输入框。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
import type { MessageBoxData } from '@ns/ui'
const result = ref('')
const handle = (promise: Promise<MessageBoxData>) => {
promise
.then(({ value }) => {
result.value = `输入了:${value}`
})
.catch(() => {})
}
const byPattern = () => {
handle(
NsMessageBox.prompt('请输入邮箱', '提示', {
inputPattern: /^[^@\s]+@[^@\s]+\.[^@\s]+$/,
inputErrorMessage: '邮箱格式不正确'
})
)
}
const byMessage = () => {
handle(
NsMessageBox.prompt('请设置密码', '提示', {
inputValidator: (value) => value.length >= 6 || '至少 6 位'
})
)
}
const byFalse = () => {
handle(
NsMessageBox.prompt('请输入数量', '提示', {
inputValidator: (value) => /^\d+$/.test(value)
})
)
}
const alertWithInput = () => {
handle(
NsMessageBox.alert('配置了 inputPlaceholder,alert 也会显示输入框', '提示', {
inputPlaceholder: '随便输入点什么'
})
)
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="byPattern">正则(inputPattern)</NsButton>
<NsButton @click="byMessage">校验函数返回字符串</NsButton>
<NsButton @click="byFalse">校验函数返回 false</NsButton>
<NsButton @click="alertWithInput">alert 带输入框</NsButton>
</NsSpace>
<p style="margin-top: 12px">{{ result || '输入不合法时点确定看看提示' }}</p>
</template>
消息类型
type 有 success、warning、info、error 四种,标题前面显示对应颜色的图标。不写时没有图标。
<script setup lang="ts">
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
import type { MessageBoxMessageType } from '@ns/ui'
const show = (type?: MessageBoxMessageType) => {
NsMessageBox.alert(`type 是 ${type ?? '不写'}`, type ?? '没有图标', { type }).catch(() => {})
}
</script>
<template>
<NsSpace wrap>
<NsButton type="success" @click="show('success')">成功(success)</NsButton>
<NsButton type="warning" @click="show('warning')">警告(warning)</NsButton>
<NsButton type="info" @click="show('info')">信息(info)</NsButton>
<NsButton type="danger" @click="show('error')">错误(error)</NsButton>
<NsButton @click="show()">不写 type</NsButton>
</NsSpace>
</template>
按钮
confirmButtonText、cancelButtonText改按钮文字。confirmButtonType、cancelButtonType改按钮类型,可选primary、success、warning、danger、info、default。确定按钮默认primary,取消按钮默认default。showConfirmButton、showCancelButton控制显示哪个按钮。
第一行每个按钮打开一个确定按钮类型不同的确认框:
<script setup lang="ts">
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
import type { MessageBoxOptions } from '@ns/ui'
type ButtonType = NonNullable<MessageBoxOptions['confirmButtonType']>
const types: ButtonType[] = ['primary', 'success', 'warning', 'danger', 'info', 'default']
const open = (message: string, options: MessageBoxOptions) => {
NsMessageBox.confirm(message, '提示', options).catch(() => {})
}
</script>
<template>
<NsSpace direction="vertical" align="start">
<NsSpace wrap>
<span class="row-label">确定按钮</span>
<NsButton
v-for="type in types"
:key="type"
:type="type"
@click="open(`confirmButtonType 是 ${type}`, { confirmButtonType: type })"
>
{{ type }}
</NsButton>
</NsSpace>
<NsSpace wrap>
<span class="row-label">其他</span>
<NsButton
@click="
open('按钮文字改成了“提交”和“再想想”', {
confirmButtonText: '提交',
cancelButtonText: '再想想'
})
"
>
自定义文字
</NsButton>
<NsButton
@click="
open('取消按钮用 danger 类型', { cancelButtonType: 'danger', cancelButtonText: '放弃' })
"
>
取消按钮的类型
</NsButton>
<NsButton @click="open('只有取消按钮', { showConfirmButton: false })">
不显示确定按钮
</NsButton>
<NsButton @click="open('确认框不显示取消按钮', { showCancelButton: false })">
不显示取消按钮
</NsButton>
</NsSpace>
</NsSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--ns-text-color-secondary);
font-size: var(--ns-font-size-sm);
}
</style>
关闭前确认
beforeClose(action, done) 在弹框要关闭前调用,action 是 'confirm'、'cancel' 或 'close'。调用 done() 才会关闭,不调用就一直开着,适合点确定后先等接口返回。prompt 点确定时,输入校验通过后才会调用它。
下面点确定后用定时器模拟提交,1.5 秒后才关闭;提交期间点取消、按 Esc 都不关闭:
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessage, NsMessageBox } from '@ns/ui'
const result = ref('')
const submit = () => {
let submitting = false
NsMessageBox.confirm('确定提交吗?', '提示', {
beforeClose: (action, done) => {
if (submitting) return
if (action !== 'confirm') {
done()
return
}
submitting = true
NsMessage.info('提交中,1.5 秒后关闭')
setTimeout(done, 1500)
}
})
.then(() => {
result.value = '提交成功'
})
.catch((action) => {
result.value = `没有提交(${action})`
})
}
</script>
<template>
<NsButton type="primary" @click="submit">提交</NsButton>
<p style="margin-top: 12px">{{ result || '还没有提交' }}</p>
</template>
callback 写法
callback(action) 在弹框关闭时调用,参数和 beforeClose 的 action 一样。传了 callback 时 Promise 照样会 resolve 或 reject,取消和关闭时仍然要写 catch,否则会出现未处理的 reject。
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessageBox } from '@ns/ui'
const result = ref('')
const open = () => {
NsMessageBox.confirm('关闭时调用 callback', '提示', {
callback: (action) => {
result.value = `callback 收到的 action:${action}`
}
}).catch(() => {})
}
</script>
<template>
<NsButton @click="open">打开确认框</NsButton>
<p style="margin-top: 12px">{{ result || '分别点确定、取消、× 看看' }}</p>
</template>
居中和圆角按钮
center 为 true 时标题、内容和按钮都居中,关闭按钮仍在右上角。roundButton 为 true 时按钮是圆角的。
<script setup lang="ts">
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
import type { MessageBoxOptions } from '@ns/ui'
const open = (message: string, options: MessageBoxOptions) => {
NsMessageBox.confirm(message, '提示', { type: 'warning', ...options }).catch(() => {})
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="open('标题、内容和按钮都居中', { center: true })">居中(center)</NsButton>
<NsButton @click="open('按钮是圆角的', { roundButton: true })"
>圆角按钮(roundButton)</NsButton
>
<NsButton @click="open('居中,按钮也是圆角', { center: true, roundButton: true })">
两个都开
</NsButton>
</NsSpace>
</template>
只能点按钮关闭
showClose: false 去掉右上角的关闭按钮,closeOnClickModal: false 点遮罩不关闭,closeOnPressEscape: false 按 Esc 不关闭。三个都关掉后,只能点下面的按钮关闭。
<script setup lang="ts">
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
import type { MessageBoxOptions } from '@ns/ui'
const open = (message: string, options: MessageBoxOptions) => {
NsMessageBox.confirm(message, '提示', options).catch(() => {})
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="open('右上角没有关闭按钮', { showClose: false })">
不显示关闭按钮(showClose)
</NsButton>
<NsButton @click="open('点遮罩不关闭', { closeOnClickModal: false })">
点遮罩不关闭(closeOnClickModal)
</NsButton>
<NsButton @click="open('按 Esc 不关闭', { closeOnPressEscape: false })">
按 Esc 不关闭(closeOnPressEscape)
</NsButton>
<NsButton
type="primary"
@click="
open('请选择一项继续', {
showClose: false,
closeOnClickModal: false,
closeOnPressEscape: false
})
"
>
三个都关掉
</NsButton>
</NsSpace>
</template>
内容传 VNode 或 HTML
message 可以传字符串、用 h() 创建的 VNode 或组件。传 VNode 时用配置对象的写法。
dangerouslyUseHTMLString 为 true 时,字符串类型的 message 按 HTML 渲染,见注意事项。不开时字符串按纯文本显示,标签会原样显示出来。
<script setup lang="ts">
import { h } from 'vue'
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
const showVNode = () => {
NsMessageBox.alert({
title: '提示',
message: h('p', ['订单 ', h('b', '20260101001'), ' 已提交'])
}).catch(() => {})
}
const showHtml = () => {
NsMessageBox.alert('<strong>加粗的内容</strong>', '提示', {
dangerouslyUseHTMLString: true
}).catch(() => {})
}
const showText = () => {
NsMessageBox.alert('<strong>加粗的内容</strong>', '提示').catch(() => {})
}
</script>
<template>
<NsSpace wrap>
<NsButton @click="showVNode">VNode</NsButton>
<NsButton @click="showHtml">HTML 字符串(dangerouslyUseHTMLString)</NsButton>
<NsButton @click="showText">普通字符串:标签原样显示</NsButton>
</NsSpace>
</template>
遮罩和页面滚动
modal 默认是 true,为 false 时不画半透明遮罩,但弹框外面仍然点不到页面,点空白处照样按 closeOnClickModal 关闭。lockScroll 默认是 true,打开期间页面不能滚动,关闭后恢复。
<script setup lang="ts">
import { NsButton, NsMessageBox, NsSpace } from '@ns/ui'
</script>
<template>
<NsSpace wrap>
<NsButton
@click="NsMessageBox.alert('没有半透明遮罩', '提示', { modal: false }).catch(() => {})"
>
不显示遮罩(modal: false)
</NsButton>
<NsButton
@click="
NsMessageBox.alert('打开期间仍然可以滚动页面', '提示', { lockScroll: false }).catch(
() => {}
)
"
>
不锁定滚动(lockScroll: false)
</NsButton>
</NsSpace>
</template>
关闭全部
NsMessageBox.close() 关闭当前所有弹框,有淡出动画。用这种方式关闭时,Promise 既不 resolve 也不 reject,一直不结束;beforeClose 和 callback 也不会调用。
下面打开的提示框 2 秒后由 NsMessageBox.close() 关掉:
<script setup lang="ts">
import { ref } from 'vue'
import { NsButton, NsMessageBox } from '@ns/ui'
const status = ref('')
const open = () => {
let settled = false
status.value = 'Promise 等待中'
NsMessageBox.alert('2 秒后自动调用 NsMessageBox.close() 关闭', '提示')
.then(() => {
settled = true
status.value = '点了确定,Promise resolve 了'
})
.catch((action) => {
settled = true
status.value = `Promise reject 了:${action}`
})
setTimeout(() => {
if (settled) return
NsMessageBox.close()
status.value = '已调用 NsMessageBox.close(),Promise 既没有 resolve 也没有 reject'
}, 2000)
}
</script>
<template>
<NsButton @click="open">打开,2 秒后关闭全部</NsButton>
<p style="margin-top: 12px">{{ status || '还没有打开' }}</p>
</template>
调用方式
| 写法 | 说明 |
|---|---|
NsMessageBox(message, title?, options?) | 按配置打开弹框。默认只有确定按钮,没有输入框 |
NsMessageBox(message, options?) | 同上,不传标题 |
NsMessageBox(options) | 同上,全部写在配置里 |
NsMessageBox.alert(...) | 提示框,默认不显示取消按钮 |
NsMessageBox.confirm(...) | 确认框,默认显示取消按钮 |
NsMessageBox.prompt(...) | 输入框,默认显示取消按钮,占位文字默认是“请输入内容” |
NsMessageBox.close() | 关闭当前所有弹框,没有返回值 |
alert、confirm、prompt 都支持三种写法:(message, title, options)、(message, options)、(options)。配置里写了 showCancelButton、inputPlaceholder 时,以配置为准。
除了 close(),其他写法都返回 Promise<MessageBoxData>:
| 怎么关闭的 | Promise 的结果 |
|---|---|
| 点确定 | resolve { action: 'confirm', value },value 是输入框的内容,没有输入框时是空字符串 |
| 点取消 | reject 'cancel' |
| 点关闭按钮、按 Esc、点遮罩 | reject 'close' |
调用 NsMessageBox.close() | 不结束 |
配置项
| 配置项 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| title | string | — | 标题 |
| message | string | VNode | Component | — | 内容 |
| type | 'success' | 'warning' | 'info' | 'error' | — | 类型,标题前显示对应的图标。不写时没有图标 |
| zIndex | number | 从 2001 开始递增 | 弹框的层级。不写时每打开一个弹框加 1,后打开的在上面 |
| confirmButtonText | string | '确定' | 确定按钮的文字 |
| cancelButtonText | string | '取消' | 取消按钮的文字 |
| confirmButtonType | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default' | 'primary' | 确定按钮的类型 |
| cancelButtonType | 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default' | 'default' | 取消按钮的类型 |
| showConfirmButton | boolean | true | 是否显示确定按钮 |
| showCancelButton | boolean | false | 是否显示取消按钮。confirm、prompt 默认是 true |
| showClose | boolean | true | 是否显示右上角的关闭按钮 |
| closeOnClickModal | boolean | true | 点遮罩(弹框外面)是否关闭 |
| closeOnPressEscape | boolean | true | 按 Esc 是否关闭 |
| center | boolean | false | 标题、内容和按钮是否居中 |
| roundButton | boolean | false | 按钮是否用圆角 |
| dangerouslyUseHTMLString | boolean | false | 是否把字符串类型的 message 当 HTML 渲染 |
| modal | boolean | true | 是否显示遮罩 |
| lockScroll | boolean | true | 打开期间是否锁定页面滚动 |
| beforeClose | (action: MessageBoxAction, done: () => void) => void | — | 关闭前调用,调用 done() 才关闭 |
| callback | (action: MessageBoxAction) => void | — | 关闭时调用。传了它 Promise 照样 resolve 或 reject |
| inputPlaceholder | string | — | 输入框的占位文字。prompt 默认是 '请输入内容'。写了它就显示输入框 |
| inputPattern | RegExp | — | 点确定时用来校验输入内容的正则。写了它就显示输入框 |
| inputValidator | (value: string) => boolean | string | — | 点确定时校验输入内容,返回 false 或字符串表示不通过。写了它就显示输入框 |
| inputErrorMessage | string | '输入的数据不合法!' | 校验不通过时的提示 |
类型
import type {
MessageBoxType,
MessageBoxMessageType,
MessageBoxAction,
MessageBoxProps,
MessageBoxOptions,
MessageBoxData,
MessageBoxInstance,
MessageBoxShortcut,
MessageBoxFn
} from '@ns/ui'
import type { Component, VNode } from 'vue'
type MessageBoxType = 'alert' | 'confirm' | 'prompt'
type MessageBoxMessageType = 'success' | 'warning' | 'info' | 'error'
type MessageBoxAction = 'confirm' | 'cancel' | 'close'
interface MessageBoxProps {
title?: string
message?: string | VNode | Component
type?: MessageBoxMessageType
zIndex?: number
confirmButtonText?: string
cancelButtonText?: string
confirmButtonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default'
cancelButtonType?: 'primary' | 'success' | 'warning' | 'danger' | 'info' | 'default'
showConfirmButton?: boolean
showCancelButton?: boolean
showClose?: boolean
closeOnClickModal?: boolean
closeOnPressEscape?: boolean
center?: boolean
roundButton?: boolean
dangerouslyUseHTMLString?: boolean
beforeClose?: (action: MessageBoxAction, done: () => void) => void
callback?: (action: MessageBoxAction) => void
inputPlaceholder?: string
inputPattern?: RegExp
inputValidator?: (value: string) => boolean | string
inputErrorMessage?: string
modal?: boolean
lockScroll?: boolean
}
type MessageBoxOptions = MessageBoxProps
interface MessageBoxData {
value?: string
action: MessageBoxAction
}
interface MessageBoxInstance {
id: string
vm: HTMLElement
props: MessageBoxOptions
close: () => void
}
/** alert、confirm、prompt 支持的三种写法 */
interface MessageBoxShortcut {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(options: MessageBoxOptions): Promise<MessageBoxData>
}
interface MessageBoxFn {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(options: MessageBoxOptions): Promise<MessageBoxData>
alert: MessageBoxShortcut
confirm: MessageBoxShortcut
prompt: MessageBoxShortcut
close(): void
}
MessageBoxInstance 是内部记录每个弹框用的类型,调用方拿不到实例。另外导出了弹框本身的组件 NsMessageBoxComponent,NsMessageBox 内部用它渲染,一般不需要直接用。
注意事项
dangerouslyUseHTMLString会把message当 HTML 直接插进页面,不做任何过滤。不要用在用户输入或接口返回的内容上,否则可能被注入脚本(XSS)。只需要加粗、换行等简单格式时,用 VNode 更安全。alert被关闭按钮、Esc 或遮罩关掉时也会 reject,不写catch会出现未处理的 reject。- 键盘操作:打开后焦点移进弹框(prompt 是在输入框里),Tab 键只在弹框里循环;Esc 只关最上面的一层,在对话框里再弹出的消息弹框按 Esc 不会把对话框一起关掉;关闭后焦点回到打开前的元素。
- 每个弹框都是单独创建的 Vue 应用,
message传的 VNode 或组件拿不到当前应用的全局组件、provide和插件,里面用到的组件要直接 import。 - 不写
zIndex时层级从 2001 开始一直递增,会盖住z-index为 2000 的对话框和抽屉。消息弹框是单独创建的应用,不读NsConfigProvider的zIndex,要改层级时在调用参数里传zIndex。先打开消息弹框、再打开对话框时,对话框会在下面。
优化点
- [ ] 支持自定义图标
- [ ] 支持拖动弹框
- [ ] 支持输入框类型(如
inputType: 'textarea')和初始值 - [ ] 确定、取消按钮支持加载状态,配合
beforeClose等接口时不用自己处理重复点击