使用 vuex 插入本地存储

Insert localstorage with vuex

我的脚本我使用的是 axios 和 vuex,但是有必要在脚本中将 formData 更改为 Json 并且它从 POST/loginB2B 200 api, 但它不会插入到本地存储中,因此它不会指向仪表板页面。

**Auth.js**

import axios from "axios";

const state = {
  user: null,
};

const getters = {
  isAuthenticated: (state) => !!state.user,
  StateUser: (state) => state.user,
};

  async LogIn({commit}, user) {
    await axios.post("loginB2B", user);
    await commit("setUser", user.get("email"));
  },

  async LogOut({ commit }) {
    let user = null;
    commit("logout", user);
  },
};

**Login.vue**

methods: {
    ...mapActions(["LogIn"]),
    async submit() {
      /*const User = new FormData();
      User.append("email", this.form.username)
      User.append("password", this.form.password)*/
      try {
          await this.LogIn({
            "email": this.form.username,
            "password": this.form.password
          })
          this.$router.push("/dashboard")
          this.showError = false
      } catch (error) {
        this.showError = true
      }
    },
  },

app.vue

  name: "App",
  created() {
    const currentPath = this.$router.history.current.path;
    if (window.localStorage.getItem("authenticated") === "false") {
      this.$router.push("/login");
    }
    if (currentPath === "/") {
      this.$router.push("/dashboard");
    }
  },
};

api /loginB2B returns 200 但它不会创建重定向到仪表板的存储。

我使用这个例子,但我需要传递 json 而不是 formData: https://www.smashingmagazine.com/2020/10/authentication-in-vue-js/

这里有几个问题:

  • 您进行了 window.localStorage.getItem 调用,但您从未在我们能看到的任何地方进行 window.localStorage.setItem 调用,因此该项目可能始终为空。在这里使用 localStorage 似乎也没有充分的理由,因为您只能访问您的 vuex 商店。我注意到在 link 中你提供了他们使用 vuex-persistedstate 包。默认情况下,这会在 vuex 键下将内容存储在 localStorage 中,但您不应该手动查询它。
  • 您正在 App.vue 中使用 created 生命周期挂钩,它通常是您启动应用程序时挂载的主要组件。这也意味着此生命周期挂钩中的代码在您登录之前执行,或者在应用程序中真正执行任何操作。而是使用 vue-router 中的 Route Navigation Guards (https://router.vuejs.org/guide/advanced/navigation-guards.html).
  • 不相关,但您没有检查 axios post 调用的响应,这意味着您总是依赖此调用 returning 一个不在 200 和 299 之间的状态代码,并且没有人也不会改变导致错误的状态代码范围以及导致响应的代码。扩大“成功”状态代码的范围并基于此执行自己的全局代码的情况并不少见。这些类型的端点 return 一个 200 OK 状态代码和一个指示没有登录发生的响应正文也很常见,以便在前端更容易地显示对用户有用的东西。这可能会导致人们使用无效凭据登录。
  • 无关,但 vuex 突变总是同步的。你永远不应该 await 他们。

没有简单的方法可以解决您的问题,因此我建议从一开始就使其稳健。

为了正确解决您的问题,我建议在 router.js 中使用全局导航守卫,用 meta 键标记哪些路由需要身份验证,哪些路由需要身份验证不要,让全局导航守卫决定是否让你加载新路线。看起来您 link 编辑的文章采用了类似的方法。为了完整起见,我也将 post 放在这里供任何访问者使用。

首先,修改 router/index.js 下的路由器文件,以包含有关您包含的路由的元信息。通过从定义商店的文件中导入商店来加载商店。然后,我们将使用 Global Navigation Guard beforeEach 来检查用户是否可以继续使用该路线。

我们为每个路由定义 requiresAuth 元键,以检查是否需要在某人未登录时重定向他们。

router/index.js

import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '../store';

Vue.use(VueRouter);
const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: {
      requiresAuth: false
    }
  }
];

// Create a router with the routes we just defined
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// This navigation guard is called everytime you go to a new route,
// including the first route you try to load
router.beforeEach((to, from, next) => {
  // to is the route object that we want to go to
  const requiresAuthentication = to.meta.requiresAuth;

  // Figure out if we are logged in
  const userIsLoggedIn = store.getters['isAuthenticated']; // (maybe auth/isAuthenticated if you are using modules)

  if (
    (!requiresAuthentication) ||
    (requiresAuthentication && userIsLoggedIn)
  ) {
    // We meet the requirements to go to our intended destination, so we call
    // the function next without any arguments to go where we intended to go
    next();

    // Then we return so we do not run any other code
    return;
  }

  // Oh dear, we did try to access a route while we did not have the required
  // permissions. Let's redirect the user to the login page by calling next
  // with an object like you would do with `this.$router.push(..)`.
  next({ name: 'Login' });
});

export default router;

现在您可以从 App.vue 中删除 created 挂钩。现在当你手动更改地址栏中的 url 或使用 this.$router.push(..)this.$router.replace(..) 时,它会检查此功能,如果你不允许访问它,则会将你重定向到登录页面.