Message 消息提示
消息提示组件,用于操作反馈提示,与 Toast 类似但位置不同(顶部居中)。
函数式调用(推荐)
Nuxt 环境使用
在 Nuxt 中,Message 涉及 DOM 操作,需要确保只在客户端执行:
Nuxt 插件方式(推荐)
创建 plugins/message.client.ts:
typescript
import { useMessage as useMessageCore } from "moongate-vue"
export default defineNuxtPlugin(() => {
const message = useMessageCore()
return {
provide: {
message,
},
}
})1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
然后在组件中使用:
vue
<script setup>
import { Button } from "moongate-vue"
// 在 Nuxt 环境中使用 $message
// const { $message } = useNuxtApp()
const handleClick = () => {
// $message.success("操作成功")
console.log("在 Nuxt 环境中,$message 可用")
}
</script>
<template>
<Button @click="handleClick" label="显示提示" />
</template>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
注意:插件文件名必须包含
.client后缀,确保只在客户端执行。
组件式调用
自定义图标
API
Props
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
modelValue | boolean | false | 是否显示(v-model) |
message | string | '' | 消息内容 |
type | 'success' | 'error' | 'warning' | 'info' | 'info' | 消息类型 |
duration | number | 3000 | 持续时间(毫秒),0 表示不自动关闭 |
closable | boolean | false | 是否显示关闭按钮 |
icon | string | '' | 自定义图标 |
Slots
| 名称 | 说明 |
|---|---|
default | 消息内容(优先级高于 message prop) |
icon | 自定义图标 |
Events
| 事件 | 参数 | 说明 |
|---|---|---|
update:modelValue | (value: boolean) | 显示状态变化时触发 |
close | — | 关闭时触发 |
useMessage API
方法
| 方法 | 参数 | 说明 |
|---|---|---|
show | (options: MessageOptions) | 显示消息 |
success | (message: string, options?) | 成功消息 |
error | (message: string, options?) | 错误消息 |
warning | (message: string, options?) | 警告消息 |
info | (message: string, options?) | 信息消息 |
MessageOptions
| 属性 | 类型 | 默认值 | 说明 |
|---|---|---|---|
message | string | — | 消息内容 |
type | 'success' | 'error' | 'warning' | 'info' | 'info' | 消息类型 |
duration | number | 3000 | 持续时间 |
closable | boolean | false | 是否可关闭 |
icon | string | '' | 自定义图标 |
Message vs Toast
| 特性 | Message | Toast |
|---|---|---|
| 位置 | 顶部居中 | 右上角 |
| 动画 | 淡入淡出 | 右侧滑入 |
| 使用场景 | 常规操作反馈 | 轻量提示 |
| 持久化 | 自动消失 | 自动消失 |
注意事项
- 推荐使用
useMessage函数式调用,代码更简洁 - Nuxt 环境中:需要确保在客户端执行,使用
if (import.meta.client)判断 - Nuxt 插件:建议使用
.client.ts后缀,或使用import.meta.client判断 - 同时显示多条消息时会堆叠显示(后出现的在下方)
- 消息会自动消失,也可手动关闭(需启用
closable) - 移动端自动适配铺满宽度