Vuex+axios传JSON调用登录接口成功未写入localStorage无法跳转问题
问题根因
- 错误调用FormData专属API:调整为JSON传参后,传入Vuex action的
user是普通JS对象,没有FormData的get()方法,user.get("email")执行报错,导致后续commit、路由跳转逻辑中断 - 缺失localStorage写入逻辑:现有代码全程没有向localStorage写入
authenticated标识和用户信息的逻辑,App.vue的权限判断自然读取不到正确状态 - 缺失Vuex mutations定义:你贴出的Auth.js代码中没有定义
setUser、logout两个mutation,commit调用无法更新state
修复代码
1. 修正Auth.js完整代码
import axios from "axios"; const state = { user: null, }; const getters = { isAuthenticated: (state) => !!state.user, StateUser: (state) => state.user, }; const actions = { async LogIn({commit}, user) { // 可根据接口返回判断登录是否成功,如有返回token可同步存储 await axios.post("loginB2B", user); // 直接读取JSON对象的email属性,无需调用get方法 await commit("setUser", user.email); }, async LogOut({ commit }) { commit("logout"); }, }; // 补全mutations定义,新增localStorage操作逻辑 const mutations = { setUser(state, email) { state.user = email; // 写入登录状态到localStorage window.localStorage.setItem("authenticated", "true"); window.localStorage.setItem("userEmail", email); }, logout(state) { state.user = null; // 退出时清除localStorage存储的状态 window.localStorage.removeItem("authenticated"); window.localStorage.removeItem("userEmail"); } }; export default { state, getters, actions, mutations }
2. 优化App.vue初始化逻辑
name: "App", created() { // 页面刷新时从localStorage恢复Vuex的用户状态 const authenticated = window.localStorage.getItem("authenticated") === "true"; const userEmail = window.localStorage.getItem("userEmail"); if (authenticated && userEmail) { this.$store.commit("setUser", userEmail); } const currentPath = this.$router.history.current.path; // 未登录时非登录页全部跳转至登录页 if (!authenticated && currentPath !== "/login") { this.$router.push("/login"); } if (currentPath === "/") { this.$router.push("/dashboard"); } },
3. Login.vue无需额外修改,现有传JSON的逻辑符合要求
补充校验点
- 确认后端
loginB2B接口已经适配JSON格式的请求体,不会因为Content-Type问题处理参数失败 - 如果接口要求登录后返回鉴权token,建议在LogIn action中拿到token后也存入localStorage,后续接口请求放在请求头中携带
内容的提问来源于stack exchange,提问作者Code Hard
相关产品推荐
相关产品推荐

