【发布时间】:2021-06-21 03:34:33
【问题描述】:
我在项目的身份验证期间将 id 信息保存到本地存储。如果用户刷新页面并登录了,我希望他停留在当前路由上,如果他没有登录,他会被引导到登录页面。实际上我做的一切都是正确的;但它一定是一个被忽视的细节。
1)我在App.vue中创建项目时调用initAuth动作
created() {
this.$store.dispatch("initAuth");
},
-
initAuth({ commit }) { let id = localStorage.getItem("id"); let fullName = localStorage.getItem("fullName"); if (id && fullName) { commit("updateUserInfo", { id, fullName }); } },
3)然后 updateUserInfo 突变正在运行
updateUserInfo(state, payload) {
state.id = payload.id;
state.fullName = payload.fullName;
},
4) 在 getter 中,我根据 state.id 返回一个结果
isLoggedIn(state) {
return state.id !== "";
},
5)那我要按照这个状态在路由器上操作;但即使 id 存在,isLoggedIn 也会返回 false !!
Vue.use(VueRouter);
console.log(store.getters.getUser);
console.log(store.getters.isLoggedIn);
const routes = [
{
path: "/",
name: "Home",
component: Home,
beforeEnter: (to, from, next) => {
if (store.getters.isLoggedIn) {
next();
} else {
next("/giris-yap");
}
},
},
{
path: "/giris-yap",
name: "Login",
component: Login,
beforeEnter: (to, from, next) => {
if (store.getters.isLoggedIn) {
next("/");
} else {
next();
}
},
},....
【问题讨论】:
标签: vue.js vuex vue-router