MessageBox 訊息彈框
模仿系統的 alert、confirm、prompt,在視窗中間彈出一個帶遮罩的小對話框,用來提示、確認操作或讓使用者輸入一項內容。用函式呼叫,回傳 Promise。
引入
import { HuiMessageBox } from '@nscode/handy-ui'
基礎用法
HuiMessageBox.alert(message, title) 彈出只有“確定”按鈕的提示框。點確定時 Promise resolve,點右上角的關閉按鈕時 reject 'close',所以也要寫 catch。預設不響應 Esc 和遮罩點擊;顯式將 closeOnPressEscape 或 closeOnClickModal 設為 true 後,對應方式關閉時也 reject 'close'。
直接呼叫 HuiMessageBox(message, title, options) 的預設效果和 alert 一樣,只有確定按鈕。
<script setup lang="ts">
import { HuiButton, HuiMessage, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const open = () => {
HuiMessageBox.alert('這是一條提示資訊', '提示', { confirmButtonText: '知道了' })
.then(() => HuiMessage.success('點了確定'))
.catch((action) => HuiMessage.info(`關掉了:${action}`))
}
const openDirect = () => {
HuiMessageBox('直接呼叫 HuiMessageBox,預設只有確定按鈕', '提示').catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open">顯示提示框(alert)</HuiButton>
<HuiButton @click="openDirect">直接呼叫 HuiMessageBox()</HuiButton>
</HuiSpace>
</template>
確認框
HuiMessageBox.confirm 預設帶“取消”按鈕。點確定時 resolve;點取消時 reject 'cancel';點關閉按鈕、按 Esc、點遮罩時 reject 'close',需要區分時看 reject 的值。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox } from '@nscode/handy-ui'
const result = ref('')
const remove = async () => {
try {
await HuiMessageBox.confirm('確定要刪除這條記錄嗎?', '刪除確認', {
confirmButtonText: '刪除',
confirmButtonType: 'danger',
type: 'warning'
})
} catch (action) {
// action 是 'cancel' 或 'close'
result.value = `沒有刪除,reject 的值是 '${action}'`
return
}
result.value = '已刪除'
}
</script>
<template>
<HuiButton type="danger" @click="remove">刪除</HuiButton>
<p style="margin-top: 12px">{{ result || '點按鈕,再分別點刪除、取消、× 試試' }}</p>
</template>
輸入框
HuiMessageBox.prompt 在內容下面顯示輸入框,預設帶“取消”按鈕,提示文字預設隨語言(中文:請輸入內容)。打開後焦點直接在輸入框裡,單行輸入按 Enter 確認。確認後回傳 MessageBoxPromptData,其中 action 為 'confirm',value 始終是字串,空輸入回傳 ''。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const name = ref('')
const rename = async (placeholder?: string) => {
try {
const { value } = await HuiMessageBox.prompt('請輸入新的名稱', '重新命名', {
inputPlaceholder: placeholder
})
name.value = value
} catch {
// 取消或關閉時不改名稱
}
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="rename('不超過 20 個字')">重新命名(自訂提示文字)</HuiButton>
<HuiButton @click="rename()">重新命名(預設提示文字)</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">目前名稱:{{ name || '未命名' }}</p>
</template>
輸入初始值
inputValue 只在本次建立彈框時讀取,不是受控值。開啟後修改傳入配置,不會取代正在編輯的草稿;每次呼叫各自讀取初始值,顯式 '' 會以空輸入開啟。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const name = ref('現有名稱')
const rename = async (empty = false) => {
try {
const { value } = await HuiMessageBox.prompt('請輸入名稱', '重新命名', {
inputValue: empty ? '' : name.value
})
name.value = value
} catch {
// 取消時保留原值。
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="rename()">以目前名稱開啟</HuiButton>
<HuiButton @click="rename(true)">以空字串開啟</HuiButton>
</HuiSpace>
<span>已儲存名稱:{{ name || '未命名' }}</span>
</HuiSpace>
</template>
輸入類型
inputType 支援 text、password、number、textarea,數字輸入仍回傳字串。多行輸入按 Enter 換行,Ctrl+Enter 或 Cmd+Enter 確認;輸入法組合期間的 Enter 不會確認。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxInputType, MessageBoxPromptData } from '@nscode/handy-ui'
const result = ref('尚未儲存輸入')
const open = async (inputType: MessageBoxInputType) => {
try {
const data: MessageBoxPromptData = await HuiMessageBox.prompt('修改後確認', '輸入類型', {
inputType,
inputValue:
inputType === 'number' ? '123' : inputType === 'textarea' ? '第一行\n第二行' : '現有內容'
})
result.value = `${data.action}:${JSON.stringify(data.value)};類型:${typeof data.value}`
} catch (action) {
result.value = `未儲存:${action}`
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="open('text')">text 文字</HuiButton>
<HuiButton @click="open('password')">password 密碼</HuiButton>
<HuiButton @click="open('number')">number 數字</HuiButton>
<HuiButton @click="open('textarea')">textarea 多行</HuiButton>
</HuiSpace>
<span>多行輸入:Enter 換行,Ctrl/Cmd+Enter 確認。</span>
<span role="status">{{ result }}</span>
</HuiSpace>
</template>
面板寬度與樣式
width、class、style 作用於本次呼叫的實際 .hui-message-box__container 面板。數字寬度使用 px,也接受 CSS 寬度;預設最大寬度為 90vw,窄螢幕會自動縮小。style 的同名屬性優先於 width,其他呼叫不會繼承本次樣式。從 scoped 樣式表設定傳送到 body 的面板時,需使用全域選擇器。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const result = ref('尚未開啟')
const open = async (width: string | number) => {
try {
await HuiMessageBox.confirm('面板適應窄螢幕,遮罩仍覆蓋整個頁面。', '本次面板樣式', {
width,
class: ['message-box-demo-panel'],
style: { borderRadius: 'var(--hui-border-radius-xl)', padding: 'var(--hui-spacing-6)' }
})
result.value = '已確認'
} catch (action) {
result.value = `未確認:${action}`
}
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="open(520)">width: 520</HuiButton>
<HuiButton @click="open('40rem')">width: 40rem</HuiButton>
</HuiSpace>
<span role="status">{{ result }}</span>
</HuiSpace>
</template>
輸入驗證
點確定時按下面的順序驗證輸入內容,不通過時在輸入框下面顯示錯誤,彈框不關閉:
inputPattern:正規表示式不匹配時顯示inputErrorMessage。inputValidator:回傳false時顯示inputErrorMessage;回傳字串時把這個字串當錯誤提示;回傳true表示通過。
inputErrorMessage 預設隨語言(中文:輸入的資料不合法!);傳空字串時也回退到預設提示。inputValidator 回傳的錯誤字串始終保留原文,不隨語言變化。
配置了 inputPlaceholder、inputPattern、inputValidator 中的任意一項,alert、confirm 也會顯示輸入框。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxData } from '@nscode/handy-ui'
const result = ref('')
const handle = (promise: Promise<MessageBoxData>) => {
promise
.then(({ value }) => {
result.value = `輸入了:${value}`
})
.catch(() => {})
}
const byPattern = () => {
handle(
HuiMessageBox.prompt('請輸入電子郵件', '提示', {
inputPattern: /^[^@\s]+@[^@\s]+\.[^@\s]+$/,
inputErrorMessage: '電子郵件格式不正確'
})
)
}
const byMessage = () => {
handle(
HuiMessageBox.prompt('請設定密碼', '提示', {
inputValidator: (value) => value.length >= 6 || '至少 6 位'
})
)
}
const byFalse = () => {
handle(
HuiMessageBox.prompt('請輸入數量', '提示', {
inputValidator: (value) => /^\d+$/.test(value)
})
)
}
const alertWithInput = () => {
handle(
HuiMessageBox.alert('配置了 inputPlaceholder,alert 也會顯示輸入框', '提示', {
inputPlaceholder: '隨便輸入點什麼'
})
)
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="byPattern">正規表示式(inputPattern)</HuiButton>
<HuiButton @click="byMessage">驗證函式返回字串</HuiButton>
<HuiButton @click="byFalse">驗證函式返回 false</HuiButton>
<HuiButton @click="alertWithInput">alert 帶輸入框</HuiButton>
</HuiSpace>
<p style="margin-top: 12px">{{ result || '輸入不合法時點確定看看提示' }}</p>
</template>
訊息類型
type 有 success、warning、info、error 四種,標題前面顯示對應顏色的圖示。不寫時沒有圖示。
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxMessageType } from '@nscode/handy-ui'
const show = (type?: MessageBoxMessageType) => {
HuiMessageBox.alert(`type 是 ${type ?? '不寫'}`, type ?? '沒有圖示', { type }).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton type="success" @click="show('success')">成功(success)</HuiButton>
<HuiButton type="warning" @click="show('warning')">警告(warning)</HuiButton>
<HuiButton type="info" @click="show('info')">資訊(info)</HuiButton>
<HuiButton type="danger" @click="show('error')">錯誤(error)</HuiButton>
<HuiButton @click="show()">不寫 type</HuiButton>
</HuiSpace>
</template>
按鈕
confirmButtonText、cancelButtonText改按鈕文字。預設取語言包(中文:確定、取消);顯式空字串保留,不回退。confirmButtonType、cancelButtonType改按鈕類型,可選primary、success、warning、danger、info、default。確定按鈕預設primary,取消按鈕預設default。showConfirmButton、showCancelButton控制顯示哪個按鈕。
第一行每個按鈕打開一個確定按鈕類型不同的確認框:
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
type ButtonType = NonNullable<MessageBoxOptions['confirmButtonType']>
const types: ButtonType[] = ['primary', 'success', 'warning', 'danger', 'info', 'default']
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, '提示', options).catch(() => {})
}
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">確定按鈕</span>
<HuiButton
v-for="type in types"
:key="type"
:type="type"
@click="open(`confirmButtonType 是 ${type}`, { confirmButtonType: type })"
>
{{ type }}
</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">其他</span>
<HuiButton
@click="
open('按鈕文字改為「提交」和「再想想」', {
confirmButtonText: '提交',
cancelButtonText: '再想想'
})
"
>
自訂文字
</HuiButton>
<HuiButton
@click="
open('取消按鈕使用 danger 類型', { cancelButtonType: 'danger', cancelButtonText: '放棄' })
"
>
取消按鈕的類型
</HuiButton>
<HuiButton @click="open('只有取消按鈕', { showConfirmButton: false })">
不顯示確定按鈕
</HuiButton>
<HuiButton @click="open('確認框不顯示取消按鈕', { showCancelButton: false })">
不顯示取消按鈕
</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
關閉前確認
beforeClose(action) 只接收 'confirm'、'cancel' 或 'close',不再接收 done。回傳 false、resolve false、拋錯或 reject 都攔截;其餘結果(包括 undefined)放行。異常在開發環境輸出診斷,彈框保留,之後可以重試。
等待 Promise 期間採用獨占檢查,再點確定、取消、關閉按鈕、遮罩或按 Esc 都不會重複呼叫掛鉤。prompt 點確定時先做輸入驗證,通過後記下這時的輸入值,再檢查關閉;等待期間輸入框還能編輯,放行後回傳的是記下的那個已驗證的值,等待中改的內容不算。外部關閉、關閉後重開或卸載會使舊結果失效,取消不會終止業務請求本身。主動呼叫 HuiMessageBox.close() 仍繞過此掛鉤。
下面點確定後等待 1.5 秒再關閉;等待期間其他關閉操作被忽略,不需要自己維護 submitting 鎖:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const result = ref('還沒有提交')
const status = ref('')
const submit = () => {
HuiMessageBox.confirm('確定提交嗎?', '提示', {
beforeClose: async (action) => {
if (action !== 'confirm') return
status.value = '提交中,1.5秒後關閉'
await new Promise<void>((resolve) => setTimeout(resolve, 1500))
status.value = ''
return true
}
})
.then(() => {
result.value = '提交成功'
})
.catch((action) => {
result.value = `沒有提交(${action})`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton type="primary" @click="submit">提交</HuiButton>
<span>{{ status || result }}</span>
</HuiSpace>
</template>
callback 寫法
callback(action) 是關閉通知,不接管回傳的 Promise:確定仍 resolve,取消仍 reject 'cancel',關閉按鈕、Esc、遮罩或主動 close() 仍 reject 'close'。回呼先執行,Promise 按同一 action 結束;即使回呼拋錯也不會讓 Promise 永久 pending,原應用錯誤處理仍能收到異常。使用 callback 時也要處理取消分支。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const callbackResult = ref('尚未收到回呼')
const promiseResult = ref('尚未結束')
const open = () => {
promiseResult.value = '等待操作'
HuiMessageBox.confirm('關閉時同時觀察callback和Promise', '提示', {
callback: (action) => {
callbackResult.value = `callback:${action}`
}
})
.then(({ action }) => {
promiseResult.value = `resolve:${action}`
})
.catch((action) => {
promiseResult.value = `reject:${action}`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiButton @click="open">打開確認框</HuiButton>
<span>{{ callbackResult }}</span>
<span>{{ promiseResult }}</span>
</HuiSpace>
</template>
關閉檢查的結果與異常
分別打開四種檢查,點確定觀察放行或保留;攔截後取消可以正常退出。callback 和 Promise 的結果同時顯示。throw/reject 示例會產生一條預期的開發診斷。
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const guardResult = ref('尚未打開')
const guardCallback = ref('尚未回呼')
const guardStatus = ref('')
type GuardMode = 'allow' | 'deny' | 'throw' | 'reject'
const openGuard = (mode: GuardMode) => {
guardResult.value = '等待結果'
HuiMessageBox.confirm('點確定測試檢查;攔截後可點取消離開', '關閉檢查', {
beforeClose: (action) => {
if (action !== 'confirm') return
if (mode === 'deny') {
guardStatus.value = 'false攔截,彈框保留'
return false
}
if (mode === 'throw') {
guardStatus.value = '拋錯攔截,彈框保留'
throw new Error('演示關閉檢查失敗')
}
if (mode === 'reject') {
guardStatus.value = '拒絕攔截,彈框保留'
return Promise.reject(new Error('演示非同步檢查失敗'))
}
guardStatus.value = '非同步檢查中,重複操作被忽略'
return new Promise<void>((resolve) =>
setTimeout(() => {
guardStatus.value = 'undefined放行'
resolve()
}, 600)
)
},
callback: (action) => {
guardCallback.value = `callback:${action}`
}
})
.then(({ action }) => {
guardResult.value = `resolve:${action}`
})
.catch((action) => {
guardResult.value = `reject:${action}`
})
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton @click="openGuard('allow')">非同步undefined放行</HuiButton>
<HuiButton @click="openGuard('deny')">false攔截</HuiButton>
<HuiButton @click="openGuard('throw')">throw攔截</HuiButton>
<HuiButton @click="openGuard('reject')">reject攔截</HuiButton>
</HuiSpace>
<span>{{ guardStatus }}</span>
<span>{{ guardCallback }}</span>
<span>{{ guardResult }}</span>
</HuiSpace>
</template>
居中和圓角按鈕
center 為 true 時標題、內容和按鈕都居中,關閉按鈕仍在右上角。roundButton 為 true 時按鈕是圓角的。
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, '提示', { type: 'warning', ...options }).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('標題、內容和按鈕皆置中', { center: true })">居中(center)</HuiButton>
<HuiButton @click="open('按鈕使用圓角', { roundButton: true })"
>圓角按鈕(roundButton)</HuiButton
>
<HuiButton @click="open('內容置中,按鈕也使用圓角', { center: true, roundButton: true })">
兩個都開
</HuiButton>
</HuiSpace>
</template>
只能點按鈕關閉
showClose: false 去掉右上角的關閉按鈕,closeOnClickModal: false 點遮罩不關閉,closeOnPressEscape: false 按 Esc 不關閉。三個都關掉後,只能點下面的按鈕關閉。
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
import type { MessageBoxOptions } from '@nscode/handy-ui'
const open = (message: string, options: MessageBoxOptions) => {
HuiMessageBox.confirm(message, '提示', options).catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="open('右上角沒有關閉按鈕', { showClose: false })">
不顯示關閉按鈕(showClose)
</HuiButton>
<HuiButton @click="open('按遮罩不關閉', { closeOnClickModal: false })">
點遮罩不關閉(closeOnClickModal)
</HuiButton>
<HuiButton @click="open('按 Esc 不關閉', { closeOnPressEscape: false })">
按 Esc 不關閉(closeOnPressEscape)
</HuiButton>
<HuiButton
type="primary"
@click="
open('請選擇一項繼續', {
showClose: false,
closeOnClickModal: false,
closeOnPressEscape: false
})
"
>
三個都關掉
</HuiButton>
</HuiSpace>
</template>
內容傳 VNode 或 HTML
message 可以傳字串、用 h() 建立的 VNode 或元件。傳 VNode 時用配置物件的寫法。
dangerouslyUseHTMLString 為 true 時,字串類型的 message 按 HTML 呈現,見注意事項。不開時字串按純文字顯示,標籤會原樣顯示出來。
<script setup lang="ts">
import { h } from 'vue'
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
const showVNode = () => {
HuiMessageBox.alert({
title: '提示',
message: h('p', ['訂單 ', h('b', '20260101001'), ' 已提交'])
}).catch(() => {})
}
const showHtml = () => {
HuiMessageBox.alert('<strong>加粗的內容</strong>', '提示', {
dangerouslyUseHTMLString: true
}).catch(() => {})
}
const showText = () => {
HuiMessageBox.alert('<strong>加粗的內容</strong>', '提示').catch(() => {})
}
</script>
<template>
<HuiSpace wrap>
<HuiButton @click="showVNode">VNode</HuiButton>
<HuiButton @click="showHtml">HTML 字串(dangerouslyUseHTMLString)</HuiButton>
<HuiButton @click="showText">普通字串:標籤原樣顯示</HuiButton>
</HuiSpace>
</template>
遮罩和頁面捲動
modal 預設是 true,為 false 時不畫半透明遮罩,但彈框外面仍然點不到頁面,點空白處照樣按 closeOnClickModal 關閉。lockScroll 預設是 true,打開期間頁面不能捲動,關閉後恢復。
<script setup lang="ts">
import { HuiButton, HuiMessageBox, HuiSpace } from '@nscode/handy-ui'
</script>
<template>
<HuiSpace wrap>
<HuiButton
@click="HuiMessageBox.alert('沒有半透明遮罩', '提示', { modal: false }).catch(() => {})"
>
不顯示遮罩(modal: false)
</HuiButton>
<HuiButton
@click="
HuiMessageBox.alert('打開期間仍然可以捲動頁面', '提示', { lockScroll: false }).catch(
() => {}
)
"
>
不鎖定捲動(lockScroll: false)
</HuiButton>
</HuiSpace>
</template>
關閉全部
HuiMessageBox.close() 關閉目前所有彈框,有淡出動畫。主動 close() 不經過 beforeClose;Promise reject 'close';傳了 callback 時也通知 callback('close'),每個彈框只處理一次。
下面打開的提示框 2 秒後由 HuiMessageBox.close() 關掉。重複打開只保留最後一次定時任務;元件卸載會取消未執行的定時器,提前結束的 Promise 不會再觸發定時關閉:
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { HuiButton, HuiMessageBox } from '@nscode/handy-ui'
const status = ref('')
let alive = true
let revision = 0
let timer: ReturnType<typeof setTimeout> | undefined
const clearTimer = () => {
if (timer !== undefined) clearTimeout(timer)
timer = undefined
}
onBeforeUnmount(() => {
alive = false
revision++
clearTimer()
})
const open = () => {
if (!alive) return
const request = ++revision
clearTimer()
const current = () => alive && request === revision
let settled = false
status.value = 'Promise 等待中'
HuiMessageBox.alert('2 秒後自動呼叫 HuiMessageBox.close() 關閉', '提示')
.then(() => {
settled = true
if (!current()) return
clearTimer()
status.value = '點了確定,Promise resolve 了'
})
.catch((action) => {
settled = true
if (!current()) return
clearTimer()
status.value = `Promise reject 了:${action}`
})
timer = setTimeout(() => {
timer = undefined
if (settled || !current()) return
HuiMessageBox.close()
if (current()) status.value = '已呼叫 HuiMessageBox.close(),等待 close 結果'
}, 2000)
}
</script>
<template>
<HuiButton @click="open">打開,2 秒後關閉全部</HuiButton>
<p style="margin-top: 12px">{{ status || '還沒有打開' }}</p>
</template>
呼叫方式
| 寫法 | 說明 |
|---|---|
HuiMessageBox(message, title?, options?) | 按配置打開彈框。預設只有確定按鈕,沒有輸入框 |
HuiMessageBox(message, options?) | 同上,不傳標題 |
HuiMessageBox(options) | 同上,全部寫在配置裡 |
HuiMessageBox.alert(...) | 提示框,預設不顯示取消按鈕 |
HuiMessageBox.confirm(...) | 確認框,預設顯示取消按鈕 |
HuiMessageBox.prompt(...) | 輸入框,預設顯示取消按鈕,提示文字預設隨語言(中文:請輸入內容) |
HuiMessageBox.close() | 關閉目前所有彈框,沒有回傳值 |
alert、confirm、prompt 都支援三種寫法:(message, title, options)、(message, options)、(options)。配置裡寫了 showCancelButton、inputPlaceholder 時,以配置為準。
prompt 的三種寫法回傳 Promise<MessageBoxPromptData>,value: string 可直接使用;普通呼叫和 alert、confirm 仍回傳 Promise<MessageBoxData>,value 保持可選。關閉結果如下:
| 關閉方式 | Promise 的結果 |
|---|---|
| 點確定 | resolve { action: 'confirm', value },value 是點確定、通過驗證時輸入框的內容,沒有輸入框時是空字串 |
| 點取消 | reject 'cancel' |
| 點關閉按鈕、按 Esc、點遮罩 | reject 'close' |
呼叫 HuiMessageBox.close() | reject 'close';傳了 callback 時同時通知 callback('close') |
在內容裡用路由、全域元件
message 傳的 VNode 或元件,用的是應用的上下文:能用全域註冊的元件、路由(<RouterLink>、useRouter())、Pinia、i18n 這類外掛,以及 app.provide 的值。
- 全量引入(
app.use(HandyUI))時自動設定好,不用另外寫; - 按需引入時,在入口檔案裡調一次
setAppContext(app):
// main.ts
import { createApp } from 'vue'
import { setAppContext } from '@nscode/handy-ui'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
setAppContext(app)
app.mount('#app')
import { h } from 'vue'
import { RouterLink } from 'vue-router'
import { HuiMessageBox } from '@nscode/handy-ui'
HuiMessageBox.confirm(
h('span', ['这张单据已被引用,', h(RouterLink, { to: '/refs' }, () => '查看引用')]),
'提示'
).catch(() => {})
一個頁面裡有多個 Vue 應用(例如微前端)時,可以在這次呼叫的配置裡傳 appContext 指定用哪個應用,優先於預設的:HuiMessageBox({ message: '...', appContext: otherApp._context })。
HuiConfigProvider 是寫在元件樹裡的,函式呼叫讀不到它的 size、zIndex,和設沒設應用上下文無關。
配置項
| 配置項 | 類型 | 預設值 | 說明 |
|---|---|---|---|
| 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(alert 為 false) | 點擊遮罩是否關閉,顯式設定優先 |
| closeOnPressEscape | boolean | true(alert 為 false) | 按 Esc 是否關閉,顯式設定優先 |
| center | boolean | false | 標題、內容和按鈕是否居中 |
| roundButton | boolean | false | 按鈕是否用圓角 |
| dangerouslyUseHTMLString | boolean | false | 是否把字串類型的 message 當 HTML 呈現 |
| modal | boolean | true | 是否顯示遮罩 |
| lockScroll | boolean | true | 打開期間是否鎖定頁面捲動 |
| beforeClose | (action: MessageBoxAction) => boolean | void | Promise<boolean | void> | — | 獨占關閉檢查;僅 false、拋錯或拒絕攔截,undefined 放行 |
| callback | (action: MessageBoxAction) => void | - | 關閉時通知;Promise 仍按同一 action 正常 resolve/reject |
| inputPlaceholder | string | — | 輸入框的提示文字。prompt 預設隨語言(中文:請輸入內容),顯式空字串不回退。寫了它就顯示輸入框 |
| inputPattern | RegExp | — | 點確定時用來驗證輸入內容的正規表示式。寫了它就顯示輸入框 |
| inputValidator | (value: string) => boolean | string | — | 點確定時驗證輸入內容,回傳 false 或字串表示不通過。寫了它就顯示輸入框 |
| inputErrorMessage | string | 隨語言(中文:輸入的資料不合法!) | 驗證不通過時的預設提示;空字串仍回退語言包,驗證器回傳的錯誤原文優先 |
| appContext | AppContext | null | — | 呈現用的應用上下文,見“在內容裡用路由、全域元件”。不傳時用 app.use(HandyUI) 或 setAppContext(app) 設定的應用 |
| width | string | number | — | 實際面板寬度;數字使用 px,預設最大寬度為 90vw |
| class | HTMLAttributes['class'] | — | 實際面板的 class,支援字串、陣列及物件,不作用於遮罩 |
| style | StyleValue | — | 實際面板樣式,支援物件、陣列或 CSS 字串;同名屬性優先於 width |
| inputValue | string | '' | 本次建立的輸入初值,空字串有效;開啟後配置變動不覆蓋草稿,提供此項會顯示輸入框 |
| inputType | MessageBoxInputType | 'text' | text、password、number 或 textarea;number 仍回傳字串,多行以 Ctrl/Cmd+Enter 確認 |
類型
import type {
MessageBoxType,
MessageBoxMessageType,
MessageBoxAction,
MessageBoxInputType,
MessageBoxProps,
MessageBoxOptions,
MessageBoxData,
MessageBoxPromptData,
MessageBoxInstance,
MessageBoxShortcut,
MessageBoxPromptShortcut,
MessageBoxFn
} from '@nscode/handy-ui'
import type { AppContext, Component, HTMLAttributes, StyleValue, VNode } from 'vue'
type MessageBoxType = 'alert' | 'confirm' | 'prompt'
type MessageBoxMessageType = 'success' | 'warning' | 'info' | 'error'
type MessageBoxAction = 'confirm' | 'cancel' | 'close'
type MessageBoxInputType = 'text' | 'password' | 'number' | 'textarea'
interface MessageBoxProps {
title?: string
message?: string | VNode | Component
type?: MessageBoxMessageType
zIndex?: number
width?: string | 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) => boolean | void | Promise<boolean | void>
callback?: (action: MessageBoxAction) => void
/** prompt 預設取語言包,顯式空字串不回退 */
inputPlaceholder?: string
inputValue?: string
inputType?: MessageBoxInputType
inputPattern?: RegExp
inputValidator?: (value: string) => boolean | string
/** 不傳或為空時取語言包,驗證器返回的錯誤原文優先 */
inputErrorMessage?: string
modal?: boolean
lockScroll?: boolean
}
interface MessageBoxOptions extends MessageBoxProps {
class?: HTMLAttributes['class']
style?: StyleValue
/** 呈現用的應用上下文,不傳時用 app.use(HandyUI) 或 setAppContext(app) 設定的應用 */
appContext?: AppContext | null
}
interface MessageBoxData {
value?: string
action: MessageBoxAction
}
interface MessageBoxPromptData {
action: 'confirm'
value: string
}
interface MessageBoxInstance {
id: string
vm: HTMLElement
props: MessageBoxOptions
close: () => void
}
/** alert、confirm 支援的三種寫法 */
interface MessageBoxShortcut {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxData>
(options: MessageBoxOptions): Promise<MessageBoxData>
}
interface MessageBoxPromptShortcut {
(message: string, title?: string, options?: MessageBoxOptions): Promise<MessageBoxPromptData>
(message: string, options?: MessageBoxOptions): Promise<MessageBoxPromptData>
(options: MessageBoxOptions): Promise<MessageBoxPromptData>
}
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: MessageBoxPromptShortcut
close(): void
}
MessageBoxInstance 是內部記錄每個彈框用的類型,呼叫方拿不到實例。另外導出了彈框本身的元件 HuiMessageBoxComponent,HuiMessageBox 內部用它呈現,一般不需要直接用。