hookehuyr

feat(router): 添加导航守卫以保护需要登录的路由

在路由配置中添加导航守卫,确保用户在访问需要登录的页面时已登录。未登录用户将被重定向到登录页面,并携带当前路径作为重定向参数,以便登录后返回原页面。
/*
* @Date: 2025-03-20 20:36:36
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2025-03-21 15:59:36
* @LastEditTime: 2025-03-21 16:25:52
* @FilePath: /mlaj/src/router/index.js
* @Description: 文件描述
*/
......@@ -133,4 +133,36 @@ const router = createRouter({
}
})
// TAG: 需要登录才能访问的路由
const authRequiredRoutes = [
'/profile',
'/profile/activities',
'/profile/courses',
'/profile/orders',
'/profile/favorites',
'/checkout'
]
// 导航守卫
router.beforeEach((to, from, next) => {
const currentUser = JSON.parse(localStorage.getItem('currentUser'))
// 如果是登录页面且有redirect参数,未登录用户直接跳转到首页
if (to.path === '/login' && to.query.redirect && !currentUser) {
next('/')
return
}
// 检查是否需要认证
if (authRequiredRoutes.some(route => to.path.startsWith(route))) {
if (!currentUser) {
// 未登录时重定向到登录页面
next({ path: '/login', query: { redirect: to.fullPath } })
return
}
}
next()
})
export default router
......
......@@ -156,9 +156,11 @@ import { useRoute, useRouter } from 'vue-router'
import FrostedGlass from '@/components/ui/FrostedGlass.vue'
import { useAuth } from '@/contexts/auth'
import { useTitle } from '@vueuse/core';
const $route = useRoute();
const $router = useRouter();
useTitle($route.meta.title);
const router = useRouter()
const { login } = useAuth()
......