【问题标题】:My vuejs navigation guard not working as expected我的 vuejs 导航守卫没有按预期工作
【发布时间】:2020-10-25 15:38:05
【问题描述】:

我正在使用 vuex 进行状态管理 这是我的 vuex 代码,

这里我的逻辑是,如果令牌存在于本地存储中,那么它将设置 isAuthenticated 为 true,这样就可以很容易地检查路由。但是有些它是如何不起作用的。

import axios from "axios";
import router from "../../router";

const state = {
  token: localStorage.getItem("tkn") || "",
  isAuth: false,
};

const getters = {
  isAuthenticated: (state) => !!state.token,
  authStatus: (state) => state.isAuth,
};

const actions = {
  login({ commit }, loginData) {
    // commit('auth_request')
    axios
      .post("/api/adminuser/auth/login", loginData)
      .then((resp) => {
        console.log(resp);
        localStorage.setItem("tkn", resp.data.token);

        axios.defaults.headers.common["Authorization"] = resp.data.token;

        commit("setToken", resp.data.token);

        router.push("/");
      })
      .catch((err) => {
        console.log(err);

        commit("authError", err);
        localStorage.removeItem("token");
      });
  },
};

const mutations = {
  setToken: (state, token) => ((state.token = token), (state.isAuth = true)),
  authError: (state) => (state.isAuth = false),
};

export default {
  state,
  getters,
  actions,
  mutations,
};

这是我的路由器代码

import Vue from "vue";
import VueRouter from "vue-router";
import auth from "../store/modules/auth.js";

Vue.use(VueRouter);

const routes = [
  {
    path: "/signin",
    name: "signin",
    component: () => import("../components/Authentication/Signin.vue"),
  },

  {
    path: "/",
    name: "dashboard",
    component: () => import("../components/Dashboard/Dashboard.vue"),
    meta: {
      requiresAuth: true,
    },
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.name !== "signin" && auth.getters.isAuthenticated == false)
    next({ name: "signin" });
  else next();
});


export default router;

目前,如果我登录仍然可以进入登录页面,甚至无需身份验证即可进入仪表板。

【问题讨论】:

    标签: vue.js vuex vue-router vuejs-routing vue-auth


    【解决方案1】:

    请在一些文件中创建一个类似下面的函数,比如 helper.js 并在 main.js 中初始化它

    helper.js

    import axios from 'axios';
    export function initialize(store, router) 
    {  router.beforeEach((to,from,next)=>{ 
       const requiresAuth= to.matched.some(record=>record.meta.requiresAuth)
       const currentUser = store.state.isAuthenticated;
       if(requiresAuth && !currentUser){ next('/signin');} 
       else if(to.path=='/signin' && currentUser){ next('/')}
       else { next()}
      })
    }
    

    在你的 main.js 中

    import {initialize} from './helper';
    import router from './router'
    import store from './store'
    initialize(store, router);
    

    登录页面

    methods: {
    ...mapActions(["login"]),
    loginUser: function(event) {
           event.preventDefault();
           this.login({ email: this.email, password: this.password })
               .then(()=>{ this.$router.replace({name:'dashboard'})
                            //forward to this path after login
                         }).catch(()=>{console.log('login fail')   });
          }
    },
    

    【讨论】:

    • 我尝试了这些步骤,但在推送到仪表板时出现错误未捕获(承诺)错误:通过导航守卫从“/signin”转到“/”时重定向。我正在通过 vuex 的操作推送到仪表板
    【解决方案2】:

    您应该在使用之前创建商店

    // auth.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    import router from "../../router";
    
    Vue.use(Vuex)
    // ....
    export default new Vuex.Store({
     state,
     getters,
     actions,
     mutations,
    });
    

    否则auth.getters.isAuthenticated 将是函数,而不是 vuex getter。

    vuex 指南在这里https://vuex.vuejs.org/guide/

    【讨论】:

    • 我的 vuex 工作正常,它的问题与我的路由和 authguard 相关
    • 你可以console.log(auth.getters.isAuthenticated) in the router.beforEach
    • 这里我得到了什么 vue-router.esm.js?8c4f:2181 TypeError: Cannot read property 'token' of undefined
    猜你喜欢
    • 2019-07-18
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2017-10-25
    • 2015-11-17
    • 2010-10-30
    相关资源
    最近更新 更多