vue 네비게이션 가드 로그인/비로그인 시

해적왕·2023년 3월 26일
0

네비게이션 가드

네비게이션 가드(navigation guard)란 뷰 라우터로 특정 URL에 접근할 때 해당 URL의 접근을 막는 방법

{
   path: "/login",
   component: login,
   name: "login",
   beforeEnter: requireLogout(),
},

let requireLogout = () => (to, from, next) => {
  if (state.token !== null) {
    alert('로그아웃 후 이용해주세요');
    router.push('/');
    return;
  }
  next();
};
{
   path: "/mypage",
   component: mypage,
   name: "mypage",
   beforeEnter: requireLogin(),
},

let requireLogin = () => (to, from, next) => {
  if (state.token === null) {
    alert('로그인 후 이용해주세요.');
    router.push({ path: '/login' })
    return;
  }
  next();
};

이렇게 설정해주면 컴포넌트 마다 지정해줄 필요없이 한 번에 지정 가능하다.

profile
프론트엔드

0개의 댓글