实现未读消息的全局事件处理

This commit is contained in:
jxxghp
2025-06-14 14:17:26 +08:00
parent 6cefdb5d37
commit 17ee5f456a
3 changed files with 68 additions and 86 deletions

View File

@@ -13,7 +13,7 @@ import { NavMenu } from '@/@layouts/types'
import { useDisplay } from 'vuetify'
import { useI18n } from 'vue-i18n'
import { filterMenusByPermission } from '@/utils/permission'
import { checkUnreadOnStartup } from '@/utils/badge'
import { onUnreadMessage } from '@/utils/badge'
const display = useDisplay()
const appMode = inject('pwaMode')
@@ -28,9 +28,6 @@ const superUser = computed(() => userStore.superUser)
// ShortcutBar 引用
const shortcutBarRef = ref<InstanceType<typeof ShortcutBar> | null>(null)
// 未读消息检查状态
const hasCheckedUnread = ref(false)
// 获取用户权限信息
const userPermissions = computed(() => ({
is_superuser: userStore.superUser,
@@ -65,57 +62,18 @@ function goBack() {
history.back()
}
// 检查未读消息并自动打开消息弹窗
async function checkUnreadMessages() {
if (!superUser.value || hasCheckedUnread.value) {
return // 只有超级用户才能看到消息,且每次会话只检查一次
}
hasCheckedUnread.value = true
try {
const unreadCount = await checkUnreadOnStartup()
if (unreadCount > 0) {
// 等待组件完全加载并重试打开消息弹窗
await waitAndOpenMessageDialog()
}
} catch (error) {
// 静默处理错误
// 处理未读消息事件
function handleUnreadMessage(count: number) {
if (superUser.value && count > 0) {
// 延迟一点时间确保组件已渲染
setTimeout(() => {
if (shortcutBarRef.value && typeof shortcutBarRef.value.openMessageDialog === 'function') {
shortcutBarRef.value.openMessageDialog()
}
}, 500)
}
}
// 等待组件准备好并打开消息弹窗
async function waitAndOpenMessageDialog() {
const maxRetries = 5
const retryDelay = 1000 // 1秒
for (let i = 0; i < maxRetries; i++) {
// 等待一段时间确保组件加载完成
await new Promise(resolve => setTimeout(resolve, retryDelay * (i + 1)))
// 检查ShortcutBar组件是否已经准备好
if (shortcutBarRef.value && typeof shortcutBarRef.value.openMessageDialog === 'function') {
shortcutBarRef.value.openMessageDialog()
return // 成功打开,退出重试循环
}
}
}
// 监听用户状态变化
watch(
superUser,
newValue => {
if (newValue && !hasCheckedUnread.value) {
// 用户状态变为超级用户且还没检查过未读消息时,延迟检查
setTimeout(() => {
checkUnreadMessages()
}, 1000)
}
},
{ immediate: true },
)
onMounted(() => {
// 获取菜单列表
startMenus.value = getMenuList(t('menu.start'))
@@ -124,11 +82,12 @@ onMounted(() => {
organizeMenus.value = getMenuList(t('menu.organize'))
systemMenus.value = getMenuList(t('menu.system'))
// 延迟检查未读消息,确保所有组件都已加载完成
nextTick(() => {
setTimeout(() => {
checkUnreadMessages()
}, 2000) // 增加延迟时间到2秒
// 监听全局未读消息事件
const unsubscribe = onUnreadMessage(handleUnreadMessage)
// 组件卸载时清理监听
onBeforeUnmount(() => {
unsubscribe()
})
})
</script>