index.ts
2.31 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import { createRouter, createWebHistory, LocationQueryRaw } from 'vue-router';
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import usePermission from '@/hooks/permission';
import { clearToken, isLogin } from '@/utils/auth';
import PageLayout from '@/layout/index.vue';
import { useAuthorizedStore } from '@/store';
import appRoutes from './modules';
NProgress.configure({ showSpinner: false }); // NProgress Configuration
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/login',
name: 'login',
component: () => import('@/views/login/index.vue'),
meta: {
title: '登陆',
requiresAuth: false,
},
},
{
name: 'root',
path: '/',
component: PageLayout,
redirect: '/demos',
children: appRoutes,
},
{
path: '/:pathMatch(.*)*',
name: 'notFound',
redirect: '/exception/404',
meta: {
requiresAuth: true,
},
},
],
scrollBehavior() {
return { top: 0 };
},
});
router.beforeEach(async (to, from, next) => {
NProgress.start();
const authorizedStore = useAuthorizedStore();
if (from.name !== undefined) {
to.meta.from = from.name;
}
async function crossroads() {
const Permission = usePermission();
if (Permission.accessRouter(to)) {
next();
} else {
next({ name: 'exception-403' });
}
NProgress.done();
}
if (isLogin()) {
if (authorizedStore.permissions.length) {
await crossroads();
} else {
try {
await authorizedStore.syncInfo();
await crossroads();
} catch (error) {
clearToken();
next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
NProgress.done();
}
}
} else {
if (to.name === 'login') {
next();
NProgress.done();
return;
}
if (to.name === 'root') {
next({ name: 'login' });
} else {
next({ name: 'login', query: { path: to.path } as LocationQueryRaw });
}
NProgress.done();
}
});
router.afterEach(async (to) => {
sessionStorage.setItem(
'route',
to.meta?.breadcrumb?.toString() ||
to.matched
?.slice(1)
.map((item) => item.name)
.toString() ||
'dashboard'
);
});
export default router;