-
vue8(router navigation guard 네비게이션 가드)JS/vue.js 2022. 3. 14. 15:24
네비게이션 가드
: 라우터로 url 입력하면 해당 컴포넌트를 보여주는 페이지 전환이 이루어지는데 이를 막는 기능
: 페이지 전환에 조건이 필요한 경우에 사용한다. (ex. 로그인 필요한 페이지)
가드의 종류는 3
1. 전역 가드 : beforeEach()
const router = new.VueRouter({ ... }) router.beforeEach((to, from, next) => { ... })
from (가려고 하는 라우터) -> from (지금 라우터)
to 로 가려면 next 함수가 호출되어야 한다.
beforeEach 가 라우터 변환 대기 상태로 만드는거라 URL 변경을 위해서는 next() 함수 호출이 필요하다.
next(); => 바로 화면 전환 next(false); => 네비게이션 중단. from 라우터로 재설정 next('/') || next({path : '/'}) => 특정 라우터로 이동
2. 라우터 가드 : beforeEnter()
{ path: '/home', component: Home, beforeEnter : (to, from, enter) => { token 확인 로직(if (토큰) { return next();} next('/'); } }
{ path: '/about', component: About, beforeEnter : function(to, from, next) { console.log('okok'); next(); } }
이렇게 라우터 가드를 사용하면 다른 라우터에서 '/about'으로 갈때 콘솔에 다음과 같이 나온다.
3. 컴포넌트 가드 : beforeRouteEnter(), beforeRouteUpdate(), beforeRouteLeave()
beforeRouteEnter (to, from, next) { //enter before 니까 아직 컴포넌트가 아직 생성되지 않은 상태에서 수행 //this 컴포넌트 인스턴스 접근 안된다 } beforeRouteUpdate (to, from, next) { ... } beforeRouteLeave (to, from, next) { //leave before 니까 해당 컴포넌트에서 다른 컴포넌트로 화면 전환되기 전에 수행 //this 컴포넌트 인스턴트 접근 가능 }
참고 :
https://joshua1988.github.io/web-development/vuejs/vue-router-navigation-guards/
(중급) Vue.js 라우터 네비게이션 가드 알아보기
뷰 라우터를 사용할 때 알아두면 좋은 네비게이션 가드 설명. 특정 페이지로 넘어가기 전에 검증 로직 추가하기
joshua1988.github.io
https://v3.router.vuejs.org/kr/guide/advanced/navigation-guards.html
네비게이션 가드 | Vue Router
네비게이션 가드 이름에서 알 수 있듯이 vue-router가 제공하는 네비게이션 가드는 주로 리디렉션하거나 취소하여 네비게이션을 보호하는 데 사용됩니다. 라우트 탐색 프로세스에 연결하는 방법
v3.router.vuejs.org
'JS > vue.js' 카테고리의 다른 글
vue10(동적 컴포넌트 component tag / 컴포넌트 갈아끼우기) (0) 2022.03.15 vue9(props,emit) (0) 2022.03.14 에러4(Component name should always be multi-word) (0) 2022.03.14 vue7(DevExtreme-DataGrid이용하기) (0) 2022.03.11 에러3(error: Mixed spaces and tabs (no-mixed-spaces-and-tabs)) (0) 2022.03.11