라우터 네비게이션 가드를 활용하여 로그인 여부 체크 및 페이지 이동
프로젝트마다 라우터 네비게이션 가드를 사용해 로그인 상태를 확인했다.
버전이 업데이트될 때마다 약간씩 수정해보았지만, 전체적인 구조는 비슷한 것 같다.
routes meta 필드 추가
라우터의 meta 필드에 requiresAuth를 추가했다.
- requiresAuth가 true인 경우: 로그인이 필요한 페이지 - 마이페이지
- requiresAuth가 없거나 false인 경우: 로그인 체크가 필요 없는 페이지 - 로그인, 회원가입
// router
const routes = [
// 마이페이지
{
path: '/my-page',
name: 'myPage',
meta: {
title: '마이페이지',
requiresAuth: true,
},
component: () => import('@/pages/myPage/MyPage.vue'),
children: [
{
path: 'user-info',
name: 'userInfo',
meta: {
title: '회원정보',
icon: 'user-info',
},
component: () => import('@/pages/myPage/UserInfo.vue'),
},
{
path: 'aa-info',
name: 'aaInfo',
meta: {
title: 'aa정보',
icon: 'aa-info',
},
component: () => import('@/pages/myPage/AaInfo.vue'),
},
{
path: 'bb-info',
name: 'bbInfo',
meta: {
title: 'bb정보',
icon: 'bb-info',
},
component: () => import('@/pages/myPage/BbInfo.vue'),
},
],
},
// 회원가입
{
path: '/sign-up',
name: 'signUp',
meta: {
title: '회원가입',
},
component: () => import('@/pages/signUp/SignUp.vue'),
},
// 로그인
{
path: '/login',
name: 'signIn',
meta: {
title: '로그인',
},
component: () => import('@/pages/signIn/SignIn.vue'),
},
];
네비게이션 가드 추가
로그인이 필요한 페이지인데 비로그인 상태인 경우
로그인 페이지로 이동시키며 로그인 하려던 페이지의 fullPath를 함께 넘겼다.
이전에는 query로 넘겨 url뒤에 값을 붙였는데 state로 처리하니 주소창이 깔끔해져 보기 좋아졌다.
// router
router.beforeEach((to, from, next) => {
const authStore = useAuthStore();
if (to.meta.requiresAuth && !authStore.isLogin) {
return next({
name: 'signIn',
state: { redirect: to.fullPath },
});
}
next();
});
로그인 성공시 페이지 이동 처리
로그인이 성공했을 때 돌아갈 redirect 값이 있는 경우 redirect로 페이지를 이동시켰다.
// login
const { redirect } = history.state;
const res = await authStore.login(params);
if (res.result.code === '성공') {
const targetRoute = redirect || { name: 'main' };
router.push(targetRoute);
} else {
}
참고
https://router.vuejs.org/guide/advanced/navigation-guards.html
'개발 > Vue' 카테고리의 다른 글
[VUE] Scoped 스타일에서 자식 요소 스타일링 : deep() (1) | 2024.10.07 |
---|---|
[VUE3] swiper 부드럽게 흐르는 슬라이드, 일시정지 기능 추가 (0) | 2024.09.26 |
[Pinia] Setup Stores 방식에 pinia-plugin-persistedstate 사용하기 (0) | 2024.07.16 |
[Vite] webpack에서 vite로 전환하기 (0) | 2024.05.27 |
[VUE3] 새로운 데이터 바인딩 패턴: defineModel 활용하기 (0) | 2024.03.07 |