太久没更新了好懒呀,之前做了一个聊天的app,今天分享一下。
聊天首先要有通讯录,然后会话列表,最后主要是聊天部分。板块太多,这里主要分享聊天内容,主要是Signalr.js来实现的,框架用了uni-app,做简易的app用uni-app真的是太香了。
首先我们先把页面大概格局准备好,这里主要包括内容区域{查看更多历史消息,行为消息,自己发出的消息,对方发出的消息},抽屉栏{表情包,更多功能-拍照、相册、转账等},底部输入栏{输入框,发送键,录音},具体布局就看个人爱好了。
然后是创建一个chart.js来连接我们的signalr.js,以及接收消息。
var Hub = require('@/common/wwwroot/lib/signalr/miniProgramSignalr.js')
import store from '@/store';
function hubStart(token){
store.commit('$hubConnect', new Hub.HubConnection());
store.state.hubConnect.start(store.state.websiteUrl+"/chatHub",{access_token:token});
store.state.hubConnect.onOpen = res => {
console.log("成功开启连接");
}
//只管接受
store.state.hubConnect.on("system", res => {
// uni.showToast("系统消息")
})
store.state.hubConnect.on("FriendRequestReceive", res => {
let count=Number(store.state.hasNewFriend);
count++;
// console.log(count)
store.commit('$hasNewFriend', count);
});
}
function hubClose(){
store.state.hubConnect.close({ reason: "退出" })
store.commit('$hubConnect', null);
}
module.exports = {
hubStart:hubStart,
hubClose:hubClose
}
进入聊天页面会带进来一个messageId和sessionId(后端伙伴会给你的,sessionId:一个聊天室的id, messageId最新聊天内容的id),根据这两个id去获取当前聊天室的此前的聊天记录,如果此时有新消息接收,就可以根据sessionId是否相同来决定是否把该条新消息push到该聊天室的聊天框内。
onShow() {
let _self = this;
if(this.hubConnect&&this.hubConnect.openStatus){
this.hubConnect.on("MessageReceive", res => {
// console.log(res)
_self.scrollToView ="";
if(res.sessionId==_self.postData.sessionId){
_self.screenMsg(res)
}else{
return
}
});
}else{
setTimeout(function(){
_self.hubConnect.on("MessageReceive", res => {
// console.log(res)
_self.scrollToView ="";
if(res.sessionId==_self.postData.sessionId){
_self.screenMsg(res)
}else{
return
}
});
},2000)
}
this.scrollTop = 9999999;
},
// 接受消息(筛选处理)
screenMsg(msg) {
let self = this;
if(this.lastMessageId==msg.messageId){
return false
}
this.lastMessageId=msg.messageId;
this.setSingItem(msg,true,
result=>{
// self.msgList.push(result);
self.$set(self.msgList,self.msgList.length,result)
self.$nextTick(function(){
self.scrollToView="";
// console.log(self)
self.scrollToView = "_"+result.messageId;
})
if(msg.contentType