【问题标题】:Why does getter return false even though the vuex store is updated with the created hook?为什么即使使用 created 钩子更新了 vuex 存储,getter 也会返回 false?
【发布时间】:2021-06-21 03:34:33
【问题描述】:

我在项目的身份验证期间将 id 信息保存到本地存储。如果用户刷新页面并登录了,我希望他停留在当前路由上,如果他没有登录,他会被引导到登录页面。实际上我做的一切都是正确的;但它一定是一个被忽视的细节。

1)我在App.vue中创建项目时调用initAuth动作

 created() {
    this.$store.dispatch("initAuth");
  },
  1. 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();
      }
    },
  },....

6)The outputs of console.logs are as follows

【问题讨论】:

标签: vue.js vuex vue-router


【解决方案1】:

我知道路由是在 created 钩子之前创建的。因此,我将 setTimeout (..., 0) 赋予了 beforeEnter 条件。问题已解决。

【讨论】:

    猜你喜欢
    • 2018-03-25
    • 1970-01-01
    • 2021-08-15
    • 2014-05-31
    • 1970-01-01
    • 2015-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多