在App底部TabBar的消息图标上显示未读消息数量徽标和红点,实时更新未读消息数量。
在应用启动和显示时自动获取并更新未读消息数量:
// app/App.vue
import { getUnreadCount } from '@/api/message'
export default {
onLaunch() {
// 应用启动时
if (getToken()) {
this.updateUnreadMessageBadge()
this.startMessagePolling() // 启动30秒轮询
}
},
onShow() {
// 应用从后台切回前台时
if (getToken()) {
this.updateUnreadMessageBadge()
}
},
methods: {
// 更新未读消息徽标
updateUnreadMessageBadge() {
getUnreadCount().then(response => {
const count = response.data || 0
if (count > 0) {
uni.setTabBarBadge({
index: 3, // 消息页面在tabBar中的索引
text: count > 99 ? '99+' : count.toString()
})
} else {
uni.removeTabBarBadge({ index: 3 })
}
})
},
// 启动消息轮询(每30秒)
startMessagePolling() {
this.messagePollingTimer = setInterval(() => {
if (getToken()) {
this.updateUnreadMessageBadge()
} else {
this.stopMessagePolling()
}
}, 30000)
}
}
}
在消息页面标记消息为已读后立即更新徽标:
// app/pages/message/index.vue
export default {
onShow() {
this.loadMessages()
this.updateTabBarBadge() // 进入页面时更新
},
methods: {
async viewMessageDetail(message) {
// 标记为已读
if (message.isRead === '0') {
await markAsRead(message.messageId)
message.isRead = '1'
this.updateTabBarBadge() // 标记后立即更新
}
// ... 跳转逻辑
},
updateTabBarBadge() {
const unreadCount = this.messages.filter(msg => msg.isRead === '0').length
if (unreadCount > 0) {
uni.setTabBarBadge({
index: 3,
text: unreadCount > 99 ? '99+' : unreadCount.toString()
})
} else {
uni.removeTabBarBadge({ index: 3 })
}
}
}
}
首页也会加载并显示未读消息数量:
// app/pages/index.vue
export default {
onShow() {
this.loadUnreadMessageCount() // 刷新未读数量
},
methods: {
loadUnreadMessageCount() {
getUnreadCount().then(response => {
if (response.code === 200) {
this.unreadMessageCount = response.data || 0
this.updateTabBarBadge(this.unreadMessageCount)
}
})
},
updateTabBarBadge(count) {
if (count > 0) {
uni.setTabBarBadge({
index: 3,
text: count > 99 ? '99+' : count.toString()
})
} else {
uni.removeTabBarBadge({ index: 3 })
}
}
}
}
根据 pages.json 中的配置,tabBar的索引顺序为:
| 索引 | 页面 | 文本 |
|---|---|---|
| 0 | pages/index | 首页 |
| 1 | pages/task/index | 任务 |
| 2 | pages/task/create | 创建任务 |
| 3 | pages/message/index | 消息 ⭐ |
| 4 | pages/mine/index | 我的 |
因此消息页面的索引是 3。
import { getUnreadCount } from '@/api/message'
getUnreadCount().then(response => {
const count = response.data || 0
// 使用count更新徽标
})
后端接口: GET /system/message/unread/count
返回格式:json { "code": 200, "data": 5, // 未读消息数量 "msg": "查询成功" }
uni.setTabBarBadge({
index: 3, // TabBar索引
text: '5' // 显示文本(字符串类型)
})
uni.removeTabBarBadge({
index: 3 // TabBar索引
})
┌─────────┐
│ 消息 │
│ [🔴3] │ ← 红色徽标显示未读数量
└─────────┘
┌─────────┐
│ 消息 │
│ │ ← 无徽标
└─────────┘
┌─────────┐
│ 消息 │
│ [🔴99+] │ ← 显示99+
└─────────┘
app/App.vue - 全局轮询和更新app/pages/index.vue - 首页消息入口app/pages/message/index.vue - 消息列表页app/api/message.js - 消息APIapp/pages.json - TabBar配置SysMessageController.java - 消息控制器SysMessageService.java - 消息服务SysMessageMapper.xml - 消息数据查询uni.setTabBarBadge 的text参数必须是字符串实现时间: 2025-10-26
实现人: AI Assistant
状态: ✅ 已完成
版本: v1.0