import TabMenu from './data'; import { fetchMessageUnreadCount } from '../services/message/fetchMessage'; Component({ data: { active: 0, list: TabMenu, unread: 0, //未读消息数,>0 时消息tab显示红点 }, lifetimes: { attached() { //先用 globalData 缓存渲染,避免切换 tab 时红点闪没,再拉取最新 const app = getApp(); if (app && Number(app.globalData?.unread) > 0) { this.setData({ unread: Number(app.globalData.unread) }); } this.refreshUnread(); }, }, //所在 tab 页面显示时刷新(切换 tab、从其他页面返回均会触发) pageLifetimes: { show() { this.refreshUnread(); }, }, methods: { onChange(event) { this.setData({ active: event.detail.value }); wx.switchTab({ url: this.data.list[event.detail.value].url.startsWith('/') ? this.data.list[event.detail.value].url : `/${this.data.list[event.detail.value].url}`, }); }, init() { const page = getCurrentPages().pop(); const route = page ? page.route.split('?')[0] : ''; const active = this.data.list.findIndex( (item) => (item.url.startsWith('/') ? item.url.substr(1) : item.url) === `${route}`, ); this.setData({ active }); }, /** * 从服务端拉取未读消息数 * 未登录/请求失败时保持 0(不显示红点),不影响 tabbar 正常使用 * 5s 内重复触发只发一次请求(app轮询/页面onShow/tabbar show 多处触发) */ refreshUnread(force = false) { if (!wx.getStorageSync('token')) { this.setData({ unread: 0 }); const app = getApp(); if (app) app.globalData.unread = 0; return; } const now = Date.now(); if (!force && now - (this._lastFetchAt || 0) < 5000) { return; } //上一次请求尚未结束时不再发起,避免请求堆积占满并发导致页面假死 if (this._fetching) { return; } this._lastFetchAt = now; this._fetching = true; const done = () => { this._fetching = false; }; fetchMessageUnreadCount().then((res) => { if (res.code == 1) { const unread = Number(res.data?.unread_count) || 0; this.setData({ unread }); const app = getApp(); if (app) app.globalData.unread = unread; } }).catch(() => {}).then(done, done); }, /** * 供消息页主动同步未读数(读消息/全部已读后红点实时消失) */ setUnread(count) { const unread = Number(count) || 0; this.setData({ unread }); const app = getApp(); if (app) app.globalData.unread = unread; }, }, });