wlzboy
2025-10-26 ed209eeb52e8d778ab2b3e8c86a3e63a924e53ec
app/App.vue
@@ -2,10 +2,17 @@
  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: {
      // 初始化应用
@@ -16,6 +23,13 @@
        //#ifdef H5
        this.checkLogin()
        //#endif
        // 如果已登录,启动未读消息轮询
        if (getToken()) {
          this.updateUnreadMessageBadge()
          // 每30秒轮询一次
          this.startMessagePolling()
        }
      },
      initConfig() {
        this.globalData.config = config
@@ -24,6 +38,50 @@
        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
        }
      }
    }
  }