Message 消息提示
常用于主动操作后的反馈提示,以轻量浮层形式展示,可通过函数式 API 调用。
基础用法
通过 ZcMessage 函数调用,支持传入字符串或配置对象。
vue
<template>
<ZcButton type="primary" @click="showMessage">显示消息</ZcButton>
</template>
<script setup>
import { ZcMessage } from '@zc-ui/components'
const showMessage = () => {
ZcMessage('这是一条消息提示')
}
</script>不同类型
通过 type 属性设置消息类型,支持 info、success、warning、danger。
vue
<template>
<ZcButton @click="ZcMessage.info('信息提示')">Info</ZcButton>
<ZcButton type="success" @click="ZcMessage.success('成功提示')">Success</ZcButton>
<ZcButton type="warning" @click="ZcMessage.warning('警告提示')">Warning</ZcButton>
<ZcButton type="danger" @click="ZcMessage.danger('危险提示')">Danger</ZcButton>
</template>
<script setup>
import { ZcMessage } from '@zc-ui/components'
</script>可关闭与持续时间
通过 showClose 显示关闭按钮,duration 控制自动关闭时间(毫秒)。
vue
<template>
<ZcButton @click="showClosable">可关闭(持续10秒)</ZcButton>
<ZcButton @click="showPersist">常驻消息</ZcButton>
</template>
<script setup>
import { ZcMessage } from '@zc-ui/components'
const showClosable = () => {
ZcMessage({ message: '此消息10秒后自动关闭', showClose: true, duration: 10000 })
}
const showPersist = () => {
ZcMessage({ message: '此消息不会自动关闭', showClose: true, duration: 0 })
}
</script>居中显示
通过 center 属性使消息文字居中。
vue
<template>
<ZcButton @click="showCentered">居中消息</ZcButton>
</template>
<script setup>
import { ZcMessage } from '@zc-ui/components'
const showCentered = () => {
ZcMessage({ message: '居中显示的消息', center: true })
}
</script>Message API
Options
| 参数 | 说明 | 类型 | 默认值 |
|---|---|---|---|
message | 消息文字内容 | string | — |
type | 消息类型 | info | success | warning | danger | info |
duration | 显示时间(毫秒),0 为常驻 | number | 3000 |
showClose | 是否显示关闭按钮 | boolean | false |
center | 是否居中显示 | boolean | false |
offset | 距离顶部的偏移量(px) | number | 20 |
onClose | 关闭时的回调函数 | () => void | — |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
close | 消息关闭时触发 | — |
快捷方式
ZcMessage 提供以下快捷方法:
ZcMessage.info(options)- 信息提示ZcMessage.success(options)- 成功提示ZcMessage.warning(options)- 警告提示ZcMessage.danger(options)- 错误/危险提示
每个快捷方法均接受字符串或配置对象(不含 type 字段)。
导出
| 名称 | 描述 |
|---|---|
ZcMessage | 消息函数,含类型快捷方法 |
ZcMessageCloseAll | 关闭所有消息实例 |
注意事项
- SSR 兼容性:
ZcMessage依赖document对象,在 SSR 环境中调用需确保仅在客户端执行(如放在onMounted中)。 - 自动关闭:默认 3 秒后自动关闭。设置
duration: 0可实现手动关闭,此时需调用返回实例的close()方法。 - 堆叠偏移:多条消息会自动堆叠排列并计算偏移量,无需手动管理位置。
- 性能建议:避免在短时间内频繁创建大量消息实例,应及时调用
close()或ZcMessageCloseAll()清理。