vue.js+socket.io+express+mongodb打造在线聊天
在线地址观看
有喜欢的小哥哥,小姐姐请反手来个star,谢谢!有issue的欢迎提出
介绍
本项目基于vue.js+socket.io+express+mongodb实现的聊天效果, 界面以及功能参考QQ,微信技术栈- 前端: vue,vue-router,vuex,axios
- 构建: webpack,vue-cli
- 后端: express,multer(上传图片),cors(跨域处理), superagent(调用机器人接口),mongoose(操作数据库)
- 通讯: socket.io
- 数据库: mongodb
- css预处理器: sass
功能列表
- 用户注册
- 用户登录
- 群聊
- 群聊中@小美 和机器人聊天 (注意@小美和消息中间要有空格)
- 机器人聊天
- 留言板
聊天代码
前端// 聊天监听 this.socket.on('chat-msg', (msg) => { this.MsgList.push(msg) this.$nextTick(() => { this.msgDOM.scrollTop = this.msgDOM.scrollHeight }) }) // 发送消息 const MsgObj = { roomId: this.roomId, timeStamp: Date.parse(new Date()), userId: this.getUserinfo.userId, headPic: this.getUserinfo.headPic, nickname: this.getUserinfo.nickname, text: this.InputMsg } this.socket.emit('chat-msg', MsgObj) this.InputMsg = ''
后端
// 进入房间 socket.on('join-room', (info) => { // 添加到房间 socket.join(info.roomId) io.to(info.roomId).emit('join-room', info.nickname) }) // 群聊天 socket.on('chat-msg', (msg) => { saveChatMsg(msg) // 分割聊天消息,判断是否与机器人聊天 const msgArr = msg.text.split(' ') if (msgArr[0] === '@小美') { getRobotMsg({userId: msg.userId, roomId: msg.roomId, text: msgArr[1]}, (robotmsg) => { saveChatMsg(robotmsg) io.to(msg.roomId).emit('chat-msg', robotmsg) }) } io.to(msg.roomId).emit('chat-msg', msg) }) // 机器人聊天 socket.on('robot-msg', (msg) => { getRobotMsg({userId: msg.userId, text: msg.text}, (robotmsg) => { socket.emit('robot-msg', robotmsg) }) }) // 离开房间 socket.on('leave-room', (info) => { socket.leave(info.roomId) console.log(info.nickname + '离开了房间') })