2021年3月11日星期四

Vuex getter authenticated returns false in route guard. I assume it evaluates to false because at the time of calling autoLogin hasn't executed yet

So I have a /login route that renders the login view and I'm trying to make it so that if the user is already logged in, he gets redirected to another route. The problem is that when I type the url www.example.com/login, authenticated evaluates to false for some reason. This is how my code works:

Login Url:

{      path: '/login',      name: 'login',      component: Login,      beforeEnter: (to, from, next) => {          if (store.getters.authenticated) {              next({ name: "adminOrders" })          } else {              next()          }      }  },  

Vuex authentication store:

import router from '../router'  import axios from 'axios'    const authentication = {      state: {          user: null      },      mutations: {          setUser(state, user){              state.user = user              localStorage.setItem('userId', user.id);              localStorage.setItem('username', user.username);              localStorage.setItem('token', user.token);          }      },      actions: {          autoLogin({commit, dispatch}){              const userId = localStorage.getItem('userId')              const username = localStorage.getItem('username')              const token = localStorage.getItem('token')                if (!token) {                  return              }                let user = {                  id: userId,                  username: username,                  token: token              }                commit('setUser', user)                axios.interceptors.request.use(function (config) {                  config.headers.Authorization = 'Bearer ' + token                    return config              });          },      },      getters: {          authenticated: state => {              return state.user ? true : false          }      }  }    export default authentication  

And I call the autoLogin on App.vue mounted like this:

<template>      <div id="app">          <router-view/>      </div>  </template>    <script>        export default {          mounted(){              this.$store.dispatch('autoLogin');          }      }  </script>  
https://stackoverflow.com/questions/66590889/vuex-getter-authenticated-returns-false-in-route-guard-i-assume-it-evaluates-to March 12, 2021 at 05:35AM

没有评论:

发表评论