109 lines
3.2 KiB
JavaScript
109 lines
3.2 KiB
JavaScript
import TabMenu from './data';
|
|
import { fetchMessageUnreadCount } from '../services/message/fetchMessage';
|
|
Component({
|
|
data: {
|
|
active: 0,
|
|
list: TabMenu,
|
|
unread: 0, //未读消息数,>0 时消息tab显示红点
|
|
},
|
|
|
|
lifetimes: {
|
|
attached() {
|
|
// 先用全局缓存渲染,避免切换 tab 时红点闪没。网络请求交给 show,并与其他实例共用节流
|
|
const app = getApp();
|
|
const unread = app && app.globalData ? Number(app.globalData.unread) || 0 : 0;
|
|
if (unread > 0) {
|
|
this.setData({ unread });
|
|
}
|
|
},
|
|
},
|
|
|
|
// 当前 tab 显示时刷新。30s 内各实例只发一次请求
|
|
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 });
|
|
},
|
|
|
|
/**
|
|
* 从服务端拉取未读消息数
|
|
* 未登录时不显示红点。节流记在 globalData,切换 Tab 新建的 tabBar 实例也会共用
|
|
* 30s 内只发一次;消息页改未读数走 setUnread,不走这里
|
|
*/
|
|
refreshUnread(force = false) {
|
|
const app = getApp();
|
|
const token = (wx.$util && wx.$util.getToken && wx.$util.getToken()) || '';
|
|
if (!token) {
|
|
this.setData({ unread: 0 });
|
|
if (app && app.globalData) {
|
|
app.globalData.unread = 0;
|
|
}
|
|
return;
|
|
}
|
|
const now = Date.now();
|
|
const last = app && app.globalData ? Number(app.globalData.unreadFetchedAt) || 0 : 0;
|
|
if (!force && now - last < 30000) {
|
|
if (app && app.globalData) {
|
|
this.setData({ unread: Number(app.globalData.unread) || 0 });
|
|
}
|
|
return;
|
|
}
|
|
if (app && app.globalData && app.globalData.unreadFetching) {
|
|
return;
|
|
}
|
|
if (app && app.globalData) {
|
|
app.globalData.unreadFetching = true;
|
|
app.globalData.unreadFetchedAt = now;
|
|
}
|
|
const done = () => {
|
|
if (app && app.globalData) {
|
|
app.globalData.unreadFetching = false;
|
|
}
|
|
};
|
|
fetchMessageUnreadCount().then((res) => {
|
|
if (res.code == 1) {
|
|
const unread = Number(res.data?.unread_count) || 0;
|
|
this.setData({ unread });
|
|
if (app && app.globalData) {
|
|
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) {
|
|
app.globalData.unread = unread;
|
|
app.globalData.unreadFetchedAt = Date.now();
|
|
}
|
|
},
|
|
},
|
|
});
|