Files
2025-11-30 16:47:06 +08:00

126 lines
3.5 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// store/useReadMsg.js
import {
defineStore
} from 'pinia'
import {
ref,
computed,
watch
} from 'vue'
import {
msg,
$api,
} from '../common/globalFunction';
// 常量定义:消息在 TabBar 的索引位置
const TABBAR_INDEX = 3;
export const useReadMsg = defineStore('readMsg', () => {
const msgList = ref([])
// 用于自定义 Tabbar 组件的渲染
const badges = ref([{
count: 0
}, {
count: 0
}, {
count: 0
}, {
count: 0
}, {
count: 0
}])
// 计算总未读数量
const unreadCount = computed(() =>
msgList.value.reduce((sum, msg) => sum + (msg.notReadCount || 0), 0)
)
// 未读消息列表
const unreadMsgList = computed(() =>
msgList.value.filter(msg => msg.notReadCount > 0)
)
function updateBadgeEffect() {
const count = unreadCount.value
// 处理显示文本超过99显示99+
const countStr = count > 99 ? '99+' : String(count)
// 1. 更新内部状态 (用于自定义 UI)
if (badges.value[TABBAR_INDEX]) {
badges.value[TABBAR_INDEX].count = count === 0 ? 0 : countStr
}
// 2. 更新系统原生 TabBar
// 加 try-catch 防止在非 Tabbar 页面或加栽未完成时报错
try {
if (count > 0) {
uni.setTabBarBadge({
index: TABBAR_INDEX,
text: countStr
})
} else {
uni.removeTabBarBadge({
index: TABBAR_INDEX
})
}
} catch (e) {
console.warn('TabBar Badge 更新失败(可能当前非TabBar页面):', e)
}
}
watch(unreadCount, () => {
updateBadgeEffect()
console.log('value', unreadCount.value)
}, {
immediate: true
})
// 拉取消息列表
async function fetchMessages() {
try {
const res = await $api.createRequest('/app/notice/info', {
isRead: 1
}, "GET")
msgList.value = res.data || []
} catch (err) {
console.error('获取消息失败:', err)
}
}
// 设置为已读
async function markAsRead(item, index) {
const targetMsg = msgList.value[index]
if (!targetMsg) return
// 如果已经是已读,直接返回,避免无效请求
// 假设服务端逻辑是isRead=1 表示已读 (注意检查你的字段定义)
// 你的原代码判断是 if (msg.isRead === 1) return如果是这样下面请求成功应该设为 1
// 但通常未读是0已读是1。这里维持你原有的逻辑假设服务端把 notReadCount 清零
try {
let params = {
id: targetMsg.noticeId
}
await $api.createRequest('/app/notice/read?id=' + targetMsg.noticeId, params, "POST")
// 更新本地数据
msgList.value[index].notReadCount = 0
msgList.value[index].isRead = 1 // 标记已读状态
} catch (err) {
console.error('设置消息已读失败:', err)
}
}
return {
badges,
msgList,
unreadMsgList,
unreadCount,
fetchMessages,
markAsRead,
updateTabBarBadge: updateBadgeEffect
}
}, {
unistorage: true, // 开启持久化
})