Vue-Router:页面刷新后返回登录页面的视图 [英] Vue-Router: view returning to login page after page refresh

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

问题描述

我正在使用Vuejs构建应用程序并使用vue-router和vuex。我现在卡住了,因为在用户登录后,我的应用程序重定向到仪表板,但如果我刷新页面,他会再次返回登录页面。要验证用户是否已登录,我的应用程序检查localstorage是否有access_token然后他被重定向到路由器视图/或不。

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:

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:

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()
  }
}

路线:

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


推荐答案

你需要让你的isLogged函数知道刷新时的本地storege情况。

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:页面刷新后返回登录页面的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆