Vue-Router:页面刷新后视图返回登录页面

Vue-Router: view returning to login page after page refresh(Vue-Router:页面刷新后视图返回登录页面)

本文介绍了Vue-Router:页面刷新后视图返回登录页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 }
   }
 ]

解决方案

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
)

这篇关于Vue-Router:页面刷新后视图返回登录页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Vue-Router:页面刷新后视图返回登录页面

基础教程推荐