// store/useReadMsg.js import { defineStore } from 'pinia' import { ref, computed, watch } from 'vue' import { msg, $api, } from '../common/globalFunction'; // 控制消息 export const useReadMsg = defineStore('readMsg', () => { const msgList = ref([]) const badges = ref([{ count: 0 }, { count: 0 }, { count: 0 }, { count: 0 }, { count: 0 }, ]) // 计算总未读数量,基于 notReadCount 字段 const unreadCount = computed(() => msgList.value.reduce((sum, msg) => sum + (msg.notReadCount || 0), 0) ) // 未读消息列表 const unreadMsgList = computed(() => msgList.value.filter(msg => msg.notReadCount > 0) ) // 设置 TabBar 角标 function updateTabBarBadge() { const count = unreadCount.value const index = 3 const countVal = count > 99 ? '99+' : String(count) // 更新徽章数据,不直接调用 uni.removeTabBarBadge 和 uni.setTabBarBadge // 因为项目使用的是自定义 TabBar,这些方法只能在原生 TabBar 页面使用 badges.value[index] = { count: count === 0 ? 0 : countVal } // 如果需要使用原生 TabBar 的徽章功能,需要确保在 TabBar 页面中调用 // 这里只更新数据,让自定义 TabBar 组件根据数据来显示徽章 } // 拉取消息列表 async function fetchMessages() { try { $api.createRequest('/app/notice/info', {}, "GET").then((res) => { msgList.value = res.data || [] updateTabBarBadge() }) } catch (err) { console.error('获取消息失败:', err) } } // 设置为已读 async function markAsRead(item, index) { const msg = msgList.value[index] if (!msg || msg.isRead === 1) return try { let params = { id: msg.noticeId } $api.createRequest('/app/notice/read?id=' + msg.noticeId, params, "POST").then((res) => { msgList.value[index].isRead = 1 updateTabBarBadge() }) } catch (err) { console.error('设置消息已读失败:', err) } } return { badges, msgList, unreadMsgList, unreadCount, fetchMessages, markAsRead, updateTabBarBadge } })