81 lines
2.4 KiB
TypeScript
81 lines
2.4 KiB
TypeScript
// Toast通知组合式函数
|
||
export const useToast = () => {
|
||
// 移除toast函数
|
||
const removeToast = (toastId: string) => {
|
||
const toast = document.getElementById(toastId)
|
||
if (toast) {
|
||
toast.classList.remove('opacity-100', 'translate-x-0')
|
||
toast.classList.add('opacity-0', 'translate-x-full')
|
||
setTimeout(() => {
|
||
toast.remove()
|
||
}, 300)
|
||
}
|
||
}
|
||
|
||
// 将函数添加到全局对象(仅在浏览器环境中)
|
||
if (typeof window !== 'undefined') {
|
||
(window as any).removeToast = removeToast
|
||
}
|
||
|
||
const showToast = (message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info') => {
|
||
// 创建toast容器(如果不存在)
|
||
let toastContainer = document.getElementById('toast-container')
|
||
if (!toastContainer) {
|
||
toastContainer = document.createElement('div')
|
||
toastContainer.id = 'toast-container'
|
||
toastContainer.className = 'fixed top-4 right-4 z-50 space-y-2'
|
||
document.body.appendChild(toastContainer)
|
||
}
|
||
|
||
// 创建toast元素
|
||
const toast = document.createElement('div')
|
||
const toastId = `toast-${Date.now()}`
|
||
toast.id = toastId
|
||
|
||
// 根据类型设置样式
|
||
const typeClasses = {
|
||
success: 'bg-green-100 border-green-500 text-green-700',
|
||
error: 'bg-red-100 border-red-500 text-red-700',
|
||
warning: 'bg-yellow-100 border-yellow-500 text-yellow-700',
|
||
info: 'bg-blue-100 border-blue-500 text-blue-700'
|
||
}
|
||
|
||
const iconMap = {
|
||
success: '✓',
|
||
error: '✕',
|
||
warning: '⚠',
|
||
info: 'ℹ'
|
||
}
|
||
|
||
toast.className = `flex items-center p-4 rounded-lg border-l-4 shadow-md transform transition-all duration-300 ease-in-out ${typeClasses[type]} opacity-0 translate-x-full`
|
||
|
||
toast.innerHTML = `
|
||
<div class="flex-shrink-0 mr-3">
|
||
<span class="text-lg font-bold">${iconMap[type]}</span>
|
||
</div>
|
||
<div class="flex-1">
|
||
<p class="font-medium">${message}</p>
|
||
</div>
|
||
<button onclick="removeToast('${toastId}')" class="ml-4 text-gray-400 hover:text-gray-600">
|
||
✕
|
||
</button>
|
||
`
|
||
|
||
toastContainer.appendChild(toast)
|
||
|
||
// 显示动画
|
||
setTimeout(() => {
|
||
toast.classList.remove('opacity-0', 'translate-x-full')
|
||
toast.classList.add('opacity-100', 'translate-x-0')
|
||
}, 100)
|
||
|
||
// 自动移除
|
||
setTimeout(() => {
|
||
removeToast(toastId)
|
||
}, 5000)
|
||
}
|
||
|
||
return {
|
||
showToast
|
||
}
|
||
}
|