Files
ks-app-employment-service/stores/useReadMsg.js
2025-07-22 15:20:21 +08:00

111 lines
2.6 KiB
JavaScript

// 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)
if (count === 0) {
uni.removeTabBarBadge({
index
}) // 替换为你消息页面的 TabBar index
badges.value[index] = {
count: 0
}
} else {
badges.value[index] = {
count: countVal
}
uni.setTabBarBadge({
index,
text: countVal
})
}
}
// 拉取消息列表
async function fetchMessages() {
try {
$api.createRequest('/app/notice/info', {
isRead: 1
}, "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
}
})