| | |
| | | import config from './config' |
| | | import store from '@/store' |
| | | import { getToken } from '@/utils/auth' |
| | | import { getUnreadCount } from '@/api/message' |
| | | |
| | | export default { |
| | | onLaunch: function() { |
| | | this.initApp() |
| | | }, |
| | | onShow: function() { |
| | | // 应用显示时刷新未读消息数量 |
| | | if (getToken()) { |
| | | this.updateUnreadMessageBadge() |
| | | } |
| | | }, |
| | | methods: { |
| | | // 初始化应用 |
| | |
| | | //#ifdef H5 |
| | | this.checkLogin() |
| | | //#endif |
| | | |
| | | // 如果已登录,启动未读消息轮询 |
| | | if (getToken()) { |
| | | this.updateUnreadMessageBadge() |
| | | // 每30秒轮询一次 |
| | | this.startMessagePolling() |
| | | } |
| | | }, |
| | | initConfig() { |
| | | this.globalData.config = config |
| | |
| | | if (!getToken()) { |
| | | this.$tab.reLaunch('/pages/login') |
| | | } |
| | | }, |
| | | |
| | | // 更新未读消息徽标 |
| | | updateUnreadMessageBadge() { |
| | | getUnreadCount().then(response => { |
| | | const count = response.data || 0 |
| | | console.log('未读消息数量:', count) |
| | | |
| | | if (count > 0) { |
| | | // 设置徽标 |
| | | uni.setTabBarBadge({ |
| | | index: 3, // 消息页面在tabBar中的索引位置(0开始) |
| | | text: count > 99 ? '99+' : count.toString() |
| | | }) |
| | | } else { |
| | | // 移除徽标 |
| | | uni.removeTabBarBadge({ |
| | | index: 3 |
| | | }) |
| | | } |
| | | }).catch(error => { |
| | | console.error('获取未读消息数量失败:', error) |
| | | }) |
| | | }, |
| | | |
| | | // 启动消息轮询 |
| | | startMessagePolling() { |
| | | // 每30秒轮询一次 |
| | | this.messagePollingTimer = setInterval(() => { |
| | | if (getToken()) { |
| | | this.updateUnreadMessageBadge() |
| | | } else { |
| | | // 如果用户已登出,停止轮询 |
| | | this.stopMessagePolling() |
| | | } |
| | | }, 30000) // 30秒 |
| | | }, |
| | | |
| | | // 停止消息轮询 |
| | | stopMessagePolling() { |
| | | if (this.messagePollingTimer) { |
| | | clearInterval(this.messagePollingTimer) |
| | | this.messagePollingTimer = null |
| | | } |
| | | } |
| | | } |
| | | } |