vue+socket.io+express+mongodb 实现简易多房间在线群聊(2)
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) { // ... })
// api register 注册
app.get('/api/user/register', function (req, res) { // ... })
// getAccountGroup 获取可进入的房间
app.get('/api/user/getAccountGroup', function (req, res) { // ... })
// getGroupNumber 获取当前房间的群成员
app.get('/api/user/getGroupNumber', function (req, res) { // ... })
// api getChatLog 获取当前房间的聊天记录
app.get('/api/getChatLog', function (req, res) { // ... })
app.get('*', function(req, res){
res.end('404')
})
}
更多详细的实现,请看 源码chat-vue-node ,里面保留着开发摸索时的很多注释。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持黑区网络。
