Repository navigation
Expand file tree
/
Copy pathpermission.js
More file actions
71 lines (61 loc) · 2.12 KB
/
Copy pathpermission.js
File metadata and controls
71 lines (61 loc) · 2.12 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration
const whiteList = ['/login'] // no redirect whitelist
router.beforeEach(async(to, from, next) => {
// start progress bar
NProgress.start()
// set page title
document.title = getPageTitle(to.meta.title)
// 确定用户是否已登录
const hasToken = getToken()
if (hasToken) {
// 已登录且要跳转的页面是登录页
if (to.path === '/login') {
// 如果已登录,请重定向到主页
next({ path: '/' })
NProgress.done() // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else {
// 判断当前用户是否已拉取完user_info信息
const hasUserIds = store.getters.userId && store.getters.userId > 0
if (hasUserIds) {
next()
} else {
try {
// 生成可访问的路线图
const accessRoutes = await store.dispatch('permission/generateRoutes')
// 动态添加可访问的路线
router.addRoutes(accessRoutes)
// hack方法以确保addRoutes是完整的
// 设置replace:true,因此导航不会留下历史记录
next({ ...to, replace: true })
} catch (error) {
// 删除token并进入登录页面重新登录
await store.dispatch('user/resetToken')
Message.error(error || 'Has Error')
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
}
} else {
/* has no token*/
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单中,直接进入
next()
} else {
// 其他无权访问的页面将被重定向到登录页面
next(`/login?redirect=${to.path}`)
NProgress.done()
}
}
})
router.afterEach(() => {
// 完成进度栏
NProgress.done()
})