wlzboy
2025-10-26 1626d13ec8b1a63676e63cf95c5004c4118da3b3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<script>
  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: {
      // 初始化应用
      initApp() {
        // 初始化应用配置
        this.initConfig()
        // 检查用户登录状态
        //#ifdef H5
        this.checkLogin()
        //#endif
        
        // 如果已登录,启动未读消息轮询
        if (getToken()) {
          this.updateUnreadMessageBadge()
          // 每30秒轮询一次
          this.startMessagePolling()
        }
      },
      initConfig() {
        this.globalData.config = config
      },
      checkLogin() {
        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
        }
      }
    }
  }
</script>
 
<style lang="scss">
  @import '@/static/scss/index.scss'
</style>