VueRouter Navigation Guards란?
사용자가 브라우저의 url을 이용해서 페이지를 강제로 이동할 때 이를 방지하기 위한 라우터 설정입니다.
또한 사용자에게 특정 페이지에 접근권한을 부여하거나 조건에 따른 리다이렉트 등을 설정할 때 사용합니다.
Navigation Guards 기본형
const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
// ...
})
router.beforeEach는 router에서 데이터를 먼저 받아와서 페이지를 호출하게 하는 함수이며 전역 가드입니다.
네비게이션이 트리거될 때마다 가드가 작성 순서에 따라 호출되기 전의 모든 경우에 발생합니다. 가드는 비동기식으로 실행 될 수 있으며 네비게이션은 모든 훅이 해결되기 전까지 보류 중 으로 간주됩니다.
인자 to : 이동할 페이지
- to: Route: the target Route Object being navigated to.
인자 from : 현재 페이지
- from: Route: the current route being navigated away from.
인자 next : 페이지 이동할 때 호출하는 API, next() 를 호출해야 다음 페이지로 이동 가능합니다!!
- next: Function: this function must be called to resolve the hook. The action depends on the arguments provided to next:
- next(): move on to the next hook in the pipeline. If no hooks are left, the navigation is confirmed.
- next(false): abort the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the from route.
- next('/') or next({ path: '/' }): redirect to a different location. The current navigation will be aborted and a new one will be started. You can pass any location object to next, which allows you to specify options like replace: true, name: 'home' and any option used in router-link's to prop or router.push
- next(error): (2.4.0+) if the argument passed to next is an instance of Error, the navigation will be aborted and the error will be passed to callbacks registered via router.onError().
라우터 가드 예시
// GOOD
router.beforeEach((to, from, next) => {
if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' })
else next()
})
라우터 가드 예시2 - 개별 route에 meta 속성 사용
...
Vue.use(VueRouter);
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
redirect: '/login',
},
{
path: '/login',
component: () => import('@/views/LoginPage.vue'),
},
{
path: '/main',
component: () => import('@/views/MainPage.vue'),
meta: { auth: true },
},
{
path: '*',
component: () => import('@/views/NotFoundPage.vue'),
},
],
});
router.beforeEach((to, from, next) => {
// to 페이지 속성 정보에 접근해서 값을 비교
if (to.meta.auth && !store.getters.isLogin) {
console.log('인증정보가 필요합니다');
next('/login');
return;
} else {
next();
}
});
export default router;
개별 route에 meta 속성을 사용해서 임의의 프로퍼티를 정의합니다.
meta: { auth: true } 에서 임의의 auth 프로퍼티가 true일 경우 인증이 필요한 페이지로 정의할 수 있습니다.
beforeEach 메소드 내에서 라우터 프로퍼티 접근은 to.meta.auth 와 같은 방법으로 할 수 있습니다.
Gloobal Resolve Guards
router.beforeResolve((to, from, next) => {
// 로직이 들어감.
});
router.beforeEach가 실행된 다음에 실행되는 전역 가드입니다.
참고로 vue-router 2.5버전 이후부터 사용가능합니다.
Global After Hooks
router.beforeEach와 같은 네비게이션 가드가 실행된 이후 라우터 hook이 끝난 시점에 특정 로직을 실행 시키는 router.afterEach 설정이 있습니다.
router.afterEach((to, from) => {
// ...
})
router.afterEach는 router.beforeEach 다르게 next 함수를 가지지 않으며 네비게이션에 영향도 줄 수 없습니다.
기타 RoueRouter Navigation Guards 설정
router.beforeEach 이외에도 네비게이션 가드를 설정하는 방법을 있습니다.
vue-router 공식 홈페이지를 참고해서 네비게이션 가드를 설정하는 몇 가지 방법을 소개하겠습니다.
라우트별 가드
beforeEnter 가드를 라우트의 설정 객체에 직접 정의 할 수 있습니다.
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
// ...
}
}
]
})
이러한 가드는 전역 이전 가드와 동일한 서명을 가집니다.
컴퍼넌트 내부가드
마지막으로 beforeRouteEnter 와 beforeRouteLeave를 사용하여 라우트 컴포넌트(라우터 설정으로 전달되는 컴포넌트) 안에 라우트 네비게이션 가드를 직접 정의 할 수 있습니다.
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.
}
}
beforeRouteEnter 가드는 네비게이션이 확인되기 전에 가드가 호출되어서 새로운 엔트리 컴포넌트가 아직 생성되지 않았기 때문에 this에 접근하지 못합니다.
그러나 콜백을 next에 전달하여 인스턴스에 액세스 할 수 있습니다. 네비게이션이 확인되고 컴포넌트 인스턴스가 콜백에 전달인자로 전달 될 때 콜백이 호출됩니다.
beforeRouteEnter (to, from, next) {
next(vm => {
// `vm`을 통한 컴포넌트 인스턴스 접근
})
}
beforeRouteLeave 안에서 this에 직접 접근 할 수 있습니다. leave 가드는 일반적으로 사용자가 저장하지 않은 편집 내용을 두고 실수로 라우트를 떠나는 것을 방지하는데 사용됩니다. 탐색은 next(false)를 호출하여 취소할 수 있습니다.
참고로 컨퍼넌트 내부 가드는 mixin을 통해서 모듈화를 할 수 있습니다.
Vue.use(Router)
Vue.mixin({
beforeRouteUpdate(to, from, next) {
// ...
}
})
전체 네비게이션 시나리오
- 네비게이션이 트리거됨.
- 비활성화될 컴포넌트에서 가드를 호출.
- 전역 beforeEach 가드 호출.
- 재사용되는 컴포넌트에서 beforeRouteUpdate 가드 호출. (2.2 이상)
- 라우트 설정에서 beforeEnter 호출.
- 비동기 라우트 컴포넌트 해결.
- 활성화된 컴포넌트에서 beforeRouteEnter 호출.
- 전역 beforeResolve 가드 호출. (2.5이상)
- 네비게이션 완료.
- 전역 afterEach 훅 호출.
- DOM 갱신 트리거 됨.
- 인스턴스화 된 인스턴스들의 beforeRouteEnter가드에서 next에 전달 된 콜백을 호출합니다.
https://router.vuejs.org/guide/advanced/navigation-guards.html
Navigation Guards | Vue Router
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
router.vuejs.org
https://router.vuejs.org/api/#router-start-location-3-5-0
API Reference | Vue Router
API Reference is the component for enabling user navigation in a router-enabled app. The target location is specified with the to prop. It renders as an tag with correct href by default, but can be configured with the tag prop. In addition, the link automa
router.vuejs.org
'Vue' 카테고리의 다른 글
Vue - VueRouter 설정 (0) | 2022.03.25 |
---|---|
Vue - axios 구조화(instance 활용) (0) | 2022.03.25 |
Vue - Vuex 헬퍼 함수 (0) | 2022.03.25 |
Vue - axios Interceptors (0) | 2022.03.25 |
Vue - axios (Http 통신) (0) | 2022.03.25 |
댓글