[Vue] 뷰 라우터 (Vue Router) - 네비게이션 가드(Navigation Guards)

sunyoung·2022년 4월 19일
0
post-thumbnail

네비게이션 가드 (Navigation Guards)

이름에서 알 수 있듯이 vue-router가 제공하는 네비게이션 가드는 주로 리디렉션하거나 취소하여 네비게이션을 보호하는 데 사용됩니다. 라우트 탐색 프로세스에 연결하는 방법에는 전역, 라우트별 또는 컴포넌트가 있습니다.


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.

💡 특정 url로 접근할 때 인증정보가 있는지 없는지 확인할 때 가장 흔하게 쓰임



Global Before Guard - beforeEnter()

const router = new VueRouter({ ... })

router.beforeEach((to, from, next) => {
  // ...
})
  • to: route 이동할 라우트 정보
  • from: route 이동하기 전 현재 위치의 라우트 정보
  • next: function next()함수를 호출해야만 이동함

next()

next()함수는 훅을 해결하기 위해 호출되어야만 한다.
인자값에 따라서 동작이 달라진다.

  • next() 파이프라인의 다음 훅으로 이동, 훅이 없는 경우 네비게이션 승인.

  • next(false) 현재 네비게이션을 중단. 브라우저 URL이 변경되면(사용자 또는 뒤로 버튼을 통해 수동으로 변경됨) from경로의 URL로 재설정됨.

  • next('/') or next({ path: '/' }) 다른 위치로 리디렉션. 현재 네비게이션이 중단되고 새 네비게이션이 시작.

  • next(error) (2.4.0 이후 추가) next에 전달된 인자가 Error 의 인스턴스이면 탐색이 중단되고 router.onError()를 이용해 등록 된 콜백에 에러가 전달됨.



Per-Route Guard - beforeEnter()

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})



In-Component Guards

const Foo = {
  template: `...`,
  beforeRouteEnter(to, from, next) {
    // called before the route that renders this component is confirmed.
    // does NOT have access to `this` component instance,
    // because it has not been created yet when this guard is called!
  },
  beforeRouteUpdate(to, from, next) {
    // called when the route that renders this component has changed.
    // This component being reused (by using an explicit `key`) in the new route or not doesn't change anything.
    // For example, for a route with dynamic params `/foo/:id`, when we
    // navigate between `/foo/1` and `/foo/2`, the same `Foo` component instance
    // will be reused (unless you provided a `key` to `<router-view>`), and this hook will be called when that happens.
    // has access to `this` component instance.
  },
  beforeRouteLeave(to, from, next) {
    // called when the route that renders this component is about to
    // be navigated away from.
    // has access to `this` component instance.
  }
}

출처: Navigation Guards | Vue Router

profile
💻✨

0개의 댓글