Vue-Router: view returning to login page after pag

2019-05-10 22:55发布

i'm building a app with Vuejs and using vue-router and vuex. i'm stuck now because, after the user login, my app redirect to dashboard, but if i refresh the page, he returns to login page again. to verify if user is logged, my app check the localstorage if have a access_token then he is redirected to router view "/" or not.

this is my router folder and his files:

src/router

index.js:

import Vue from 'vue'

import VueRouter from 'vue-router'

import {routes} from './routes'

import beforeEach from './beforeEach'

Vue.use(VueRouter)

const router = Vue.router = new VueRouter({
  hashbang: false,
  linkActiveClass: 'active',
  saveScrollPosition: true,
  mode: 'history',
  base: __dirname,
  routes
})


router.beforeEach(beforeEach)

export default router

beforeEach.js:

import store from '../store/store'

const isAuthRoute = route => route.path.indexOf('/login') !== -1

const isLogged = () => store.getters.isLoggedIn

export default (to, from, next) => {
  if (!isAuthRoute(to) && !isLogged()) {
    next('/login')
  } else {
    next()
  }
}

routes:

export const routes = [
   {
     path: '/',
     component: require('../components/Application/Dashboard.vue'),
     meta: { auth: true },
     children: [
       {
         path: '',
         component: require('../components/Home.vue'),
         name: 'home',
         meta: { auth: true }
       },
       {
         path: 'account',
         component: require('../components/Application/Account.vue'),
         name: 'account',
         meta: { auth: true }
       }
     ]
   },
   {
     path: '/login',
     component: require('../components/Application/Login.vue'),
     name: 'login',
     meta: { auth: false }
   },
   {
     path: '*',
     component: require('../components/PageNotFound.vue'),
     meta: { auth: false }
   }
 ]

1条回答
Deceive 欺骗
2楼-- · 2019-05-10 23:34

You will need to make your isLogged function aware of the local storege case on the refresh.

const isLogged = () => storeLoggedIn || loadSessionFromLocalStorage
const storeLoggedIn = () => store.getters.isLoggedIn
const loadSessionFromLocalStorage = () => (
  // if localstorage has token
  //   commit a mutation for loggedIn and then return true
  // else return false
)
查看更多
登录 后发表回答