feat(router): 添加导航守卫以保护需要登录的路由
在路由配置中添加导航守卫,确保用户在访问需要登录的页面时已登录。未登录用户将被重定向到登录页面,并携带当前路径作为重定向参数,以便登录后返回原页面。
Showing
2 changed files
with
35 additions
and
1 deletions
| 1 | /* | 1 | /* |
| 2 | * @Date: 2025-03-20 20:36:36 | 2 | * @Date: 2025-03-20 20:36:36 |
| 3 | * @LastEditors: hookehuyr hookehuyr@gmail.com | 3 | * @LastEditors: hookehuyr hookehuyr@gmail.com |
| 4 | - * @LastEditTime: 2025-03-21 15:59:36 | 4 | + * @LastEditTime: 2025-03-21 16:25:52 |
| 5 | * @FilePath: /mlaj/src/router/index.js | 5 | * @FilePath: /mlaj/src/router/index.js |
| 6 | * @Description: 文件描述 | 6 | * @Description: 文件描述 |
| 7 | */ | 7 | */ |
| ... | @@ -133,4 +133,36 @@ const router = createRouter({ | ... | @@ -133,4 +133,36 @@ const router = createRouter({ |
| 133 | } | 133 | } |
| 134 | }) | 134 | }) |
| 135 | 135 | ||
| 136 | +// TAG: 需要登录才能访问的路由 | ||
| 137 | +const authRequiredRoutes = [ | ||
| 138 | + '/profile', | ||
| 139 | + '/profile/activities', | ||
| 140 | + '/profile/courses', | ||
| 141 | + '/profile/orders', | ||
| 142 | + '/profile/favorites', | ||
| 143 | + '/checkout' | ||
| 144 | +] | ||
| 145 | + | ||
| 146 | +// 导航守卫 | ||
| 147 | +router.beforeEach((to, from, next) => { | ||
| 148 | + const currentUser = JSON.parse(localStorage.getItem('currentUser')) | ||
| 149 | + | ||
| 150 | + // 如果是登录页面且有redirect参数,未登录用户直接跳转到首页 | ||
| 151 | + if (to.path === '/login' && to.query.redirect && !currentUser) { | ||
| 152 | + next('/') | ||
| 153 | + return | ||
| 154 | + } | ||
| 155 | + | ||
| 156 | + // 检查是否需要认证 | ||
| 157 | + if (authRequiredRoutes.some(route => to.path.startsWith(route))) { | ||
| 158 | + if (!currentUser) { | ||
| 159 | + // 未登录时重定向到登录页面 | ||
| 160 | + next({ path: '/login', query: { redirect: to.fullPath } }) | ||
| 161 | + return | ||
| 162 | + } | ||
| 163 | + } | ||
| 164 | + | ||
| 165 | + next() | ||
| 166 | +}) | ||
| 167 | + | ||
| 136 | export default router | 168 | export default router | ... | ... |
| ... | @@ -156,9 +156,11 @@ import { useRoute, useRouter } from 'vue-router' | ... | @@ -156,9 +156,11 @@ import { useRoute, useRouter } from 'vue-router' |
| 156 | import FrostedGlass from '@/components/ui/FrostedGlass.vue' | 156 | import FrostedGlass from '@/components/ui/FrostedGlass.vue' |
| 157 | import { useAuth } from '@/contexts/auth' | 157 | import { useAuth } from '@/contexts/auth' |
| 158 | import { useTitle } from '@vueuse/core'; | 158 | import { useTitle } from '@vueuse/core'; |
| 159 | + | ||
| 159 | const $route = useRoute(); | 160 | const $route = useRoute(); |
| 160 | const $router = useRouter(); | 161 | const $router = useRouter(); |
| 161 | useTitle($route.meta.title); | 162 | useTitle($route.meta.title); |
| 163 | + | ||
| 162 | const router = useRouter() | 164 | const router = useRouter() |
| 163 | const { login } = useAuth() | 165 | const { login } = useAuth() |
| 164 | 166 | ... | ... |
-
Please register or login to post a comment