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
|
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Layout from '@/components/layout/Layout.vue';
// 懒加载路由组件
const Dashboard = () => import('@/pages/Dashboard.vue');
const Products = () => import('@/pages/Products.vue');
const ProductDetail = () => import('@/pages/ProductDetail.vue');
const Orders = () => import('@/pages/Orders.vue');
const Users = () => import('@/pages/Users.vue');
const Login = () => import('@/pages/Login.vue');
const NotFound = () => import('@/pages/NotFound.vue');
// 路由守卫
const requireAuth = (to: any, from: any, next: any) => {
const isLoggedIn = localStorage.getItem('token');
if (isLoggedIn) {
next();
} else {
next('/login');
}
};
const routes: Array<RouteRecordRaw> = [
{
path: '/login',
name: 'Login',
component: Login,
meta: { requiresAuth: false }
},
{
path: '/',
component: Layout,
meta: { requiresAuth: true },
children: [
{
path: '',
name: 'Dashboard',
component: Dashboard
},
{
path: 'products',
name: 'Products',
component: Products
},
{
path: 'products/:id',
name: 'ProductDetail',
component: ProductDetail,
props: true
},
{
path: 'orders',
name: 'Orders',
component: Orders
},
{
path: 'users',
name: 'Users',
component: Users
}
]
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: NotFound
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
scrollBehavior(to, from, savedPosition) {
if (savedPosition) {
return savedPosition;
} else {
return { top: 0 };
}
}
});
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
requireAuth(to, from, next);
} else {
next();
}
});
export default router;
|