如何获取Vuex中dispatch('getUserProfile')的返回值实现角色路由跳转
解决方案
核心逻辑:Vuex 中 dispatch 方法默认返回被触发 Action 返回值包装的 Promise,只要你在 getUserProfile 中主动返回用户数据,就可以在 signIn 中用 await 直接拿到返回结果。
步骤1:改造 getUserProfile Action,新增返回值
// Vuex Action 定义 async getUserProfile({ commit }) { // 调用后端接口获取用户数据 const res = await request.get('/api/user/profile') const userProfile = res.data // 将用户数据存入 store commit('SET_USER_PROFILE', userProfile) // 新增:把用户数据返回给调用方 return userProfile }
步骤2:改造 signIn Action,接收返回值做跳转判断
async signIn({ dispatch }, loginParams) { try { // 调用 Firebase 邮箱密码登录接口 await firebase.auth().signInWithEmailAndPassword( loginParams.email, loginParams.password ) // await 等待 getUserProfile 执行完成,直接拿到返回的用户数据 const userInfo = await dispatch('getUserProfile') // 角色判断跳转逻辑,路由实例根据你项目的实际情况引入即可 if (userInfo.roles.includes('admin')) { // 管理员跳培训页 $router.push('/training') } else { // 普通用户跳个人资料页 $router.push('/profile') } } catch (err) { // 自行补充登录失败、获取用户信息失败的错误处理 console.error('登录流程异常', err) } }
可选方案:直接从 Store 取已存储的用户数据
如果你不想修改 getUserProfile 新增返回值,也可以在 dispatch 执行完成后,直接从 Vuex 状态中读取已经存入的用户数据:
async signIn({ dispatch, state }) { // 省略登录逻辑... await dispatch('getUserProfile') // 直接读取store中已经存入的用户数据,路径根据你实际的state结构调整 const userInfo = state.user.profile // 后续跳转逻辑和上面一致 }
内容的提问来源于stack exchange,提问作者Gaurav
相关产品推荐
相关产品推荐

