GlobalToast 是基于 wot-design-uni 的 wd-toast 组件封装的全局提示组件,通过 Pinia 状态管理实现全局调用。
wd-toast 组件封装在 App.vue 或根组件中注册:
<template>
<div>
<!-- 其他内容 -->
<GlobalToast />
</div>
</template>
import { useGlobalToast } from '@/composables/useGlobalToast'
const toast = useGlobalToast()
// 普通提示
toast.show('这是一条提示信息')
// 自定义配置
toast.show({
msg: '自定义提示',
duration: 3000,
position: 'top'
})
成功提示,显示绿色成功图标
toast.success('操作成功')
toast.success({
msg: '保存成功',
duration: 2000
})
默认配置:
- 图标:success
- 持续时间:1500ms
错误提示,显示红色错误图标
toast.error('操作失败')
toast.error({
msg: '网络错误,请重试',
duration: 3000
})
默认配置:
- 图标:error
- 方向:vertical(垂直布局)
信息提示,显示蓝色信息图标
toast.info('这是一条信息')
toast.info({
msg: '请注意查看',
position: 'top'
})
默认配置:
- 图标:info
警告提示,显示黄色警告图标
toast.warning('警告信息')
toast.warning({
msg: '请谨慎操作',
iconName: 'warning'
})
默认配置:
- 图标:warning
手动关闭提示
toast.close()
| 参数 | 类型 | 默认值 | 说明 |
|---|
| msg | string | - | 提示内容 |
| duration | number | 2000 | 持续时间(ms),0表示不自动关闭 |
| position | string | 'middle' | 显示位置:'top' | 'middle' | 'bottom' |
| iconName | string | - | 图标名称 |
| direction | string | - | 布局方向:'horizontal' | 'vertical' |
| cover | boolean | false | 是否显示遮罩 |
| show | boolean | - | 是否显示(内部使用) |
所有方法都支持两种参数类型:
export default {
setup() {
const toast = useGlobalToast()
const handleSuccess = () => {
toast.success('操作成功!')
}
const handleError = () => {
toast.error('操作失败,请重试')
}
const handleCustom = () => {
toast.show({
msg: '自定义提示',
duration: 5000,
position: 'top',
iconName: 'info'
})
}
return {
handleSuccess,
handleError,
handleCustom
}
}
}
async function handleSubmit() {
const toast = useGlobalToast()
try {
// 提交数据
await submitData()
toast.success('提交成功')
}
catch (error) {
toast.error(`提交失败:${error.message}`)
}
}
function showLongMessage() {
toast.info({
msg: '这是一条很长的提示信息,可能需要更长的显示时间',
duration: 4000,
position: 'top'
})
}
toastOptions(提示配置)、currentPage(当前页面路径)export default {
options: {
virtualHost: true, // 虚拟节点
addGlobalClass: true, // 支持全局样式
styleIsolation: 'shared' // 样式隔离共享
}
}
success()error()info()warning()// ✅ 推荐做法
toast.success('操作完成')
```
duration: 0 时记得手动调用 close() 关闭