Skip to content

Toast 通知

通知组件,用于操作反馈提示。

函数式调用(推荐)

Nuxt 环境使用

在 Nuxt 中,Toast 涉及 DOM 操作,需要确保只在客户端执行:

Nuxt 插件方式(推荐)

创建 plugins/toast.client.ts

typescript
import { useToast as useToastCore } from "moongate-vue"

export default defineNuxtPlugin(() => {
  const toast = useToastCore()

  return {
    provide: {
      toast,
    },
  }
})

然后在组件中使用:

vue
<script setup>
import { Button } from "moongate-vue"

// 在 Nuxt 环境中使用 $toast
// const { $toast } = useNuxtApp()

const handleClick = () => {
  // $toast.success("操作成功")
  console.log("在 Nuxt 环境中,$toast 可用")
}
</script>

<template>
  <Button @click="handleClick" label="显示提示" />
</template>

注意:插件文件名必须包含 .client 后缀,确保只在客户端执行。

组件式调用

自定义图标

API

Props

属性类型默认值说明
modelValuebooleanfalse是否显示(v-model)
messagestring''消息内容
type'success' | 'error' | 'warning' | 'info''info'通知类型
durationnumber3000持续时间(毫秒),0 表示不自动关闭
closablebooleanfalse是否显示关闭按钮
position'top' | 'bottom''top'显示位置
iconstring''自定义图标

Slots

名称说明
default消息内容(优先级高于 message prop)
icon自定义图标

Events

事件参数说明
update:modelValue(value: boolean)显示状态变化时触发
close关闭时触发

useToast API

方法

方法参数说明
show(options: ToastOptions)显示通知
success(message: string, options?)成功通知
error(message: string, options?)错误通知
warning(message: string, options?)警告通知
info(message: string, options?)信息通知

ToastOptions

属性类型默认值说明
messagestring消息内容
type'success' | 'error' | 'warning' | 'info''info'通知类型
durationnumber3000持续时间
closablebooleanfalse是否可关闭
position'top' | 'bottom''top'显示位置
iconstring''自定义图标

注意事项

  • 推荐使用 useToast 函数式调用,代码更简洁
  • Nuxt 环境中:需要确保在客户端执行,使用 if (import.meta.client) 判断
  • Nuxt 插件:建议使用 .client.ts 后缀,或使用 import.meta.client 判断
  • 同时显示多个通知时会堆叠显示(后出现的在下方)
  • 通知会自动消失,也可手动关闭(需启用 closable
  • 支持顶部和底部两种位置
  • 移动端自动适配铺满宽度

Released under the MIT License