Skip to content

MessageBox 消息弹框

模拟系统的消息提示框,同时支持 alert、confirm 和 prompt 三种模式。

消息提示

当用户进行操作时会被触发,该对话框中断用户操作,直到用户确认知晓后才可关闭。

vue
<template>
  <x-button @click="handleAlert">消息提示</x-button>
  <x-button @click="handleSuccess">成功</x-button>
</template>

<script setup>
import { MessageBox } from '@xto/feedback'

const handleAlert = () => {
  MessageBox.alert('这是一条消息提示', '提示')
}

const handleSuccess = () => {
  MessageBox.alert('操作成功!', '成功', {
    type: 'success'
  })
}
</script>

确认消息

提示用户确认其已经触发的动作,并询问是否进行此操作。

vue
<template>
  <x-button type="danger" @click="handleConfirm">删除确认</x-button>
</template>

<script setup>
import { MessageBox } from '@xto/feedback'

const handleConfirm = async () => {
  try {
    const result = await MessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      type: 'warning'
    })
    if (result.action === 'confirm') {
      // 用户确认,执行删除操作
    }
  } catch {
    // 用户取消
  }
}
</script>

提交内容

当用户进行操作时会被触发,需要用户输入内容。

vue
<template>
  <x-button type="primary" @click="handlePrompt">输入邮箱</x-button>
</template>

<script setup>
import { MessageBox } from '@xto/feedback'

const handlePrompt = async () => {
  try {
    const result = await MessageBox.prompt('请输入邮箱', '提示', {
      inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
      inputErrorMessage: '邮箱格式不正确'
    })
    if (result.action === 'confirm') {
      console.log('用户输入:', result.value)
    }
  } catch {
    // 用户取消
  }
}
</script>

自定义

可自定义按钮文字和样式。

vue
<script setup>
import { MessageBox } from '@xto/feedback'

const handleCustom = async () => {
  const result = await MessageBox.confirm('测试内容', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    center: true
  })
}
</script>

API

方法

方法名说明参数
MessageBox.alert显示消息提示框(message, title?, options?)
MessageBox.confirm显示确认消息框(message, title?, options?)
MessageBox.prompt显示输入消息框(message, title?, options?)
MessageBox.closeAll关闭所有消息框

MessageBoxOptions

属性说明类型默认值
title标题string'提示'
message消息内容string
type消息类型'success' | 'warning' | 'info' | 'error''info'
confirmButtonText确认按钮文字string'确定'
cancelButtonText取消按钮文字string'取消'
showConfirmButton是否显示确认按钮booleantrue
showCancelButton是否显示取消按钮booleanfalse
showClose是否显示关闭按钮booleantrue
closeOnClickModal点击遮罩层是否关闭booleantrue
dangerouslyUseHTMLString是否将 message 作为 HTML 渲染booleanfalse
center是否居中布局booleanfalse
showInput是否显示输入框 (prompt)booleanfalse
inputPlaceholder输入框占位符string'请输入'
inputType输入框类型string'text'
inputPattern输入框验证正则RegExp
inputErrorMessage输入框验证失败提示string
inputValue输入框默认值string''
customClass自定义类名string

返回值

MessageBox 方法返回一个 Promise,resolve 的值是 MessageBoxResult:

属性说明类型
action用户的操作'confirm' | 'cancel' | 'close'
value输入框的值 (仅 prompt)string

基于 MIT 许可发布