| | |
| | | import { getUnreadCount } from '@/api/message' |
| | | |
| | | export default { |
| | | data() { |
| | | return { |
| | | messagePollingTimer: null, |
| | | lastToken: null // 用于检测 token 变化 |
| | | } |
| | | }, |
| | | onLaunch: function() { |
| | | this.lastToken = getToken() |
| | | this.initApp() |
| | | |
| | | // 监听用户登出事件 |
| | | uni.$on('user-logout', () => { |
| | | console.log('接收到用户登出事件,停止消息轮询') |
| | | this.stopMessagePolling() |
| | | this.lastToken = null |
| | | // 清除消息徽标 |
| | | uni.removeTabBarBadge({ index: 3 }) |
| | | }) |
| | | }, |
| | | onShow: function() { |
| | | // 应用显示时刷新未读消息数量 |
| | | if (getToken()) { |
| | | this.updateUnreadMessageBadge() |
| | | const currentToken = getToken() |
| | | |
| | | // 检测 token 变化:从有到无(登出) |
| | | if (this.lastToken && !currentToken) { |
| | | console.log('检测到用户已登出,停止消息轮询') |
| | | this.stopMessagePolling() |
| | | this.lastToken = currentToken |
| | | return |
| | | } |
| | | |
| | | // 检测 token 变化:从无到有(登录) |
| | | if (!this.lastToken && currentToken) { |
| | | console.log('检测到用户已登录,启动消息轮询') |
| | | this.lastToken = currentToken |
| | | } |
| | | |
| | | // 应用显示时刷新未读消息数量 |
| | | if (currentToken) { |
| | | this.updateUnreadMessageBadge() |
| | | // 重新启动轮询(如果之前已停止) |
| | | if (!this.messagePollingTimer) { |
| | | this.startMessagePolling() |
| | | } |
| | | } |
| | | }, |
| | | onHide: function() { |
| | | // 应用隐藏时停止轮询,节省资源 |
| | | this.stopMessagePolling() |
| | | }, |
| | | methods: { |
| | | // 初始化应用 |
| | |
| | | |
| | | // 更新未读消息徽标 |
| | | updateUnreadMessageBadge() { |
| | | // 检查是否已登录,未登录则不请求 |
| | | if (!getToken()) { |
| | | console.log('用户未登录,跳过获取未读消息数量') |
| | | return |
| | | } |
| | | |
| | | getUnreadCount().then(response => { |
| | | const count = response.data || 0 |
| | | console.log('未读消息数量:', count) |