☕ vue router (Navigation Guards) 설정

0

cuppers

목록 보기
2/2

navigation guards란?

As the name suggests, the navigation guards provided by Vue router are primarily used to guard navigations either by redirecting it or canceling it. There are a number of ways to hook into the route navigation process: globally, per-route, or in-component.
이름에서 알 수 있듯이, 네비게이션 가드는 vue 라우터에 의해 제공되는 기능입니다.
네비게이션이 변경될 때마다(라우터가 라우트가 변경될 때)마다 그것을 취소 시키거나 리다이렉팅 시킬 수 있습니다. 네비게이션 가드의 방법은 global(글로벌 가드), per-route(경로별), in-component(구성요소 내 적용) 등 여러 방법이 있습니다.

저는 cuppers 프로젝트에서 다음과 같이
Global before guards를 적용했습니다.

우선 route.js에서 route guard가 필요한 path에 대해 다음과 같이 meta: { requiresAuth: true }를 추가해줬습니다.

     .. {
        path: 'review/write/:id',
        component: () => import('src/pages/WriteReviewPage.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'my',
        component: () => import('src/pages/MyPage.vue'),
        meta: { requiresAuth: true }
      }, ..

아래와 같이 store 파라미터를 추가해주고
Router.beforeEach((to, from, next) => { ... } 부분을 추가해 주었습니다.

export default route(function ({ store }) { 
  ...
  Router.beforeEach((to, from, next) => {
    if (
      to.matched.some(
        (record) =>
          record.meta.requiresAuth && !store.getters['auth/isLoggedIn']
      )
    ) {
      Notify.create({
        position: 'top',
        timeout: 1000,
        message: '로그인이 필요한 메뉴입니다. 로그인 페이지로 이동합니다.',
        color: 'primary'
      })
      next({
        path: '/login'
      })
    } else {
      next()
    }
  })
}

결론

auth/isLoggedIn이 스토어에 저장된 auth정보가 없어서 false이고(즉, 현재 로그인중이 아니고) 이동하려는 라우트(to)가 requiredAuth:true 에 해당하는 라우트일 경우에 대해서
'로그인이 필요한 메뉴입니다.' 라는 toast 팝업과 함께 /login으로 이동합니다.

참고 문서:

https://router.vuejs.org/guide/advanced/navigation-guards.html

profile
늦깎이아재 FE 개발자 여름입니다 :)

0개의 댓글