在对需要做登录的系统前端页面访问做控制时,可以用router的beforeEach方式来对跳转到的路径做管理。如果访问的路径在路径白名单内,则可以继续访问,如果不在,则判断用户是否登录,如果未登录,则被强制跳转到登录页面。
一般在前端,用户登录完成之后,我们会将管理用户状态的token值存在Cookie或者session中,所以可以用是否有token值来判断用户是否已经做了登录。
权限判断逻辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
import router from './router'
import store from './store'
import Cookies from 'js-cookie'
const whiteList = ['/login']
router.beforeEach(async(to, from, next) => { const hasToken = Cookies.get('MySystemToken') if (hasToken) { if (to.path === '/login') { next({ path: '/'}) } else { const hasGetUserInfo = store.getters.name if (hasGetUserInfo) { next() } else { try { await store.dispatch('user/getInfo') next() } catch (error) { await store.dispatch('user/resetToken') console.log(error) next(`/login?redirect=${to.path}`) } } } } else { if (whiteList.indexOf(to.path) != -1) { next() } else { next(`/login?redirect=${to.path}`) } } })
|
写完权限判断逻辑,只需在vue框架入口的main.js中引入即可,