微信小程序接入腾讯云IM即时通讯(在微信小程序底部设置消息未读总数)
1.先看小程序api文档:
- wx.setTabBarBadge(OBJECT)
- wx.removeTabBarBadge(OBJECT)
- 这两个api对消息数量进行显示隐藏** :https://developers.weixin.qq.com/miniprogram/dev/api/ui-tabbar.html#wxsettabbarbadgeobject
首先使用本地存储,在app.js里面做定义和判断
if (wx.getStorageSync('unread') > 0 ){//消息数大于0才显示,否则隐藏
wx.setTabBarBadge({
index: 1,
text: this.data.unread
})
}else{
wx.removeTabBarBadge({
index:1,
text: ''
})
}
完整代码
//监听新消息(私聊(包括普通消息、全员推送消息),普通群(非直播聊天室)消息)事件
//newMsgList 为新消息数组,结构为[Msg]
function onMsgNotify(newMsgList) {
var newMsg;
//获取所有聊天会话
for (var j in newMsgList) {//遍历新消息
newMsg = newMsgList[j];
if (newMsg.getSession().id() == id) {//为当前聊天对象的消息
selSess = newMsg.getSession();
handlderMsg(newMsg, false);
currentMsgsArray = currentMsgsArray.map((item, index) => {
if (!item.isSelfSend) {
item.avatar = myAvatar
} else {
item.avatar = friendAvatar
}
return item;
})
var myMessages = that.setDatas(currentMsgsArray);
that.setData({
myMessages: myMessages,
})
setTimeout(function () {
if (that.data.is_chat){
that.pageScrollToBottom()
}
}, 100)
}
}
// 更新未读数
getUnread()
}
//更新消息未读数
function getUnread(){
var sess= {};
var unread = 0 ;
var sessMap = webim.MsgStore.sessMap();
if (that.data.contactList) {
// 更新消息的未读数
for (var i in sessMap) {
sess = sessMap[i];
var contactList = that.data.contactList.map((item, index) => {
if (item.To_Account == sess.id()) {
item.UnreadMsgCount = sess.unread()
}
return item;
})
that.setData({
contactList: contactList
})
//统计未读消息数量显示在底部栏
unread = that.data.contactList.reduce(function(prev,cur){
return cur.UnreadMsgCount + prev
},0)
// 获取最新的会话消息
webim.getRecentContactList({
'Count': 10 //最近的会话数 ,最大为 100
}, function (resp) {
var MsgShow = resp.SessionItem.filter((item, index) => {
if (item.To_Account == sess.id()) return item;
})
var contactList = that.data.contactList.map((item, index) => {
if (item.To_Account == sess.id()) {
// 获取最新消息
if (MsgShow[0].MsgShow == '[其他]'){
MsgShow[0].MsgShow = '[房源信息]'
}
item.MsgShow = MsgShow[0].MsgShow
}
return item;
})
that.setData({
contactList: contactList
})
})
}
}
//设置消息未读数量总数
unread = JSON.stringify(unread)
wx.setStorageSync('unread', unread)
app.data.unread = unread
if (unread != '0') {
wx.setTabBarBadge({
index: 1,
text:unread
})
} else {
wx.removeTabBarBadge({
index: 1
})
}
}
这段代码写在监听新消息onMsgNotify事件里面的更新未读数时间里面getUnread()
思路是每次获取到新消息然后把会话列表所有的未读消息数相加得出总数
这里注意一下这个参数是个string类型的
//统计未读消息数量显示在底部栏
unread = that.data.contactList.reduce(function(prev,cur){
return cur.UnreadMsgCount + prev
},0)
//设置消息未读数量总数
unread = JSON.stringify(unread)
wx.setStorageSync('unread', unread)
app.data.unread = unread
if (unread != '0') {
wx.setTabBarBadge({
index: 1,
text:unread
})
} else {
wx.removeTabBarBadge({
index: 1
})
}
有问题可以留言或者提问