Vue-Router: view returning to login page after page refresh(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:页面刷新后视图返回登录页面
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 响应更改 div 大小保持纵横比 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01