uniapp底部标签栏(Tab Bar)未读提示的实现思路

发布于:2024-05-02 ⋅ 阅读:(30) ⋅ 点赞:(0)

uniapp底部标签栏(Tab Bar)未读提示的实现思路

在移动端开发中,确保用户能够及时获悉新消息是提升用户体验的关键。有时候,我们会遇到在标签栏某一下级页面中有未读提示,但是在底部标签栏中没有提醒,导致用户不能及时了解到有未读消息的情况,下面笔者分享一种实现思路。

场景设定

我们模拟一个场景:在底部标签栏有两个标签页面,分别为:首页和我的,在我的页面下有一个未读消息页面,该页面接收未读消息并进行处理。
我们要实现的目标为:

  1. 当用户启动APP时,在“我的”导航项上显示未读消息提示及消息数量。
  2. 当用户进入未读消息进行处理并返回”我的“页面时会对未读消息条数进行实时响应。

要实现这一目标,关键在于如何实时响应未读消息的变化。这里,我们选择使用VueX来管理应用状态。

使用Vuex

在uniapp中引入VueX和VueX的使用就不进行赘述,我们直接在store文件夹下的modules文件夹下创建一个名为unreadInfo.js的js文件,并在其中写入

import { unReadCount } from '@/apis/message/message';

export default {
  namespaced: true,
  state: {
    unRedNum: 0
  },
  mutations: {
    setUnreadCount(state, count) {
      state.unRedNum = count
    }
  },
  actions: {
    async getUnReadCount({ commit }) {
      try {
        const response = await unReadCount()
        console.log(response)
        commit('setUnreadCount', response)
      } catch (error) {
        console.error('获取未读计数失败:', error)
      }
    }
  },
  getters: {
    unreadCount: state => state.unRedNum
  }
}

并且在store文件夹下进行引用

import Vue from 'vue'
import Vuex from 'vuex'

import appUnreadInfo from './modules/unread-info'

Vue.use(Vuex)

export default new Vuex.Store({
  strict: process.env.NODE_ENV !== 'production',
  modules: {
    appUnreadInfo
  },
  state: {},
  mutations: {},
  actions: {},
  getters: {}
})

使用VueX

在未读信息页面进行引入和使用VueX

import store from '@/store'

export default {
  methods: {
   toRoute(item) {
      if (item.isRead === 2) {
        read({
          messageId: item.messageId
        }).then(data => {
          uni.showToast({
            title: this.$t('str229'),
            icon: 'none'
          })
        })
        // 加载未读消息数目
        store.dispatch('appUnreadInfo/getUnReadCount')
      }
      uni.navigateTo({
        url: `/apps/me/message/me`
      })
    }
   }
  }

通过调用 read 接口处理未读消息后,我们使用 store.dispatch('appUnreadInfo/getUnReadCount') 来更新未读消息数量。 在“我的”页面,我们可以这样实现未读消息提示的更新:

import { mapGetters } from 'vuex'

onShow() {
   const unreadCount = this.$store.getters['appUnreadInfo/unreadCount']
      if (unreadCount > 1) {
        uni.setTabBarBadge({
          index: 1,
          text: unreadCount
        })
      } else {
        uni.removeTabBarBadge({
          index: 1
        })
      }
    }

调用VueX的getters方法来获取unRedNum数并使用uniapp的setTabBarBadge方法在底部标签栏进行未读消息提醒
最后我们在“首页”页面中

  computed: {
    /**
     * 实时响应未读信息
     */
    ...mapGetters('appUnreadInfo', ['unreadCount'])
  },
   onLoad(query) {
    // 加载未读消息数目
    store.dispatch('appUnreadInfo/getUnReadCount').then(() => {
      const unreadCount = this.$store.getters['appUnreadInfo/unreadCount']
      if (unreadCount > 1) {
        uni.setTabBarBadge({
          index: 1,
          text: unreadCount
        })
      } else {
        uni.removeTabBarBadge({
          index: 1
        })
      }
    })
  },

进行实时响应,使当用户刚进入app时就能接收到未读消息提醒
完成


网站公告

今日签到

点亮在社区的每一天
去签到