消息模块完善
This commit is contained in:
@@ -1,8 +1,28 @@
|
||||
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: {
|
||||
@@ -25,5 +45,42 @@ Component({
|
||||
);
|
||||
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;
|
||||
}
|
||||
this._lastFetchAt = now;
|
||||
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(() => {});
|
||||
},
|
||||
|
||||
/**
|
||||
* 供消息页主动同步未读数(读消息/全部已读后红点实时消失)
|
||||
*/
|
||||
setUnread(count) {
|
||||
const unread = Number(count) || 0;
|
||||
this.setData({ unread });
|
||||
const app = getApp();
|
||||
if (app) app.globalData.unread = unread;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user