vue+socket.io+express+mongodb 实现简易多房间在线群聊示例

2020-06-16 06:15:54易采站长站整理

const accountSchema = new Schema({
account: {type: Number}, // 用户账号
nickName: {type: String}, // 用户昵称
pass: {type: Number}, // 密码
regTime: {type: Number} // 注册时间
})
// 聊天群的数据结构模型:聊天群包含的成员
const relationSchema = new Schema({
groupAccount: Number, // 群账号
groupNickName: String, // 群昵称
groupNumber: [] // 群成员
})
// 单个聊天群的聊天消息记录
const groupSchema = new Schema({
account: Number, // 聊天者的账号
nickName: String, // 聊天者的昵称
chatTime: Number, // 发消息的时间戳
chatMes: String, // 聊天的消息内容
chatToGroup: Number, // 聊天的所在群账号
chatType: String // 消息类型:进入群、离开群、发消息
})

vue-router 路由设计

页面路由的跳转全部由前端的 vue-router 处理,页面功能少而全、仅3个:注册登录页、个人中心页、群聊页


routes: [
// {path: '/', name: 'Hello', component: Hello},
{path: '/', redirect: '/login', name: 'Hello', component: Hello},
{path: '/login', name: 'Login', component: Login},
{path: '/center', name: 'Center', component: Center},
{path: '/chatGroup', name: 'ChatGroup', component: ChatGroup}
]// 未登录时,通过编程式跳去登录页:
router.push({ path: 'login' })

vuex 全局状态

主要是通过vuex来全局管理个人账号的登录状态、当前所在群聊房间的信息:


export default new Vuex.Store({
state: {
chatState: {
account: null,
nickName: null
},
groupState: null // 点击进群的时候更新
},
mutations: {
updateChatState (state, obj) {
state.chatState = obj
},
updateGroupState (state, obj) {
state.groupState = obj
}
},
actions: {
updateChatState ({commit}, obj) {
commit('updateChatState', obj)
},
updateGroupState ({commit}, obj) {
commit('updateGroupState', obj)
}
},
getters: {
getChatState (state) {
return state.chatState
},
getGroupState (state) {
return state.groupState
}
}
})

在全局中更新state、获取state:


// 更新
this.$store.dispatch('updateChatState', {account: null, nickName: null})
// 获取
this.$store.getters.getChatState

数据库接口api


module.exports = function (app) {
app.all("*", function(req, res, next) {
next()
})
// api login 登录
app.get('/api/user/login', function (req, res) { // ... })