프로그래밍/Vue.js

[Vue.js] Vue.js Navigation Guard (beforeEach)

asvv 2020. 8. 19. 02:19

Vue.js Router Life cycle

LifeCycle

Navigation Guard 'beforeEach'

Vue.js Router의 Navigation Guard 중 하나인 'beforeEach'는 Global Guard라고도 불린다.
사용은 아래와 같다.

router.beforeEach((to, from, next) => {})
  • to: 이동할 URL 정보가 담긴 라우터 객체 (이동할 URL)
  • from: 현재 URL 정보가 담긴 라우터 객체 (현재 URL)
  • next: to에서 지정한 URL로 이동하기 위해 필수적으로 호출해야하는 함수

beforeEach(to, from, next)의 to.matched

to.matched는 return 값이 LIST이다.

router.js에서 routes의 path 중 일치하는 것을 가져온다.

// router.js
const router = new Router({
    routes: [
        {
            path: '/', // ← 이 부분 일치하는 지 확인
            name: 'HelloWorld',
            component: HelloWorld
        }
    ]
})

to.matched의 length

0인 경우는 없는 URL을 요청한 것으로 404 페이지로 가게 해주면 된다.
1인 경우는 주소 창에 해당 URL을 입력한 후 요청할 때이다. 이 경우 router.app.$storeundefined가 된다.
debugger로 확인하니 router.app.$options.store에서 vuex의 store를 가져올 수 있다.
2인 경우는 router.push를 이용했을 때이다.

beforeEach(to, from, next)의 to.meta

// router.js
const router = new Router({
    routes: [
        {
            path: '/',
            name: 'HelloWorld',
            component: HelloWorld,
            meta: {
                // 여기 정보를 가져옴
            }
        }
    ]
})

to.meta를 이용하여 각 페이지의 권한 등을 검사할 수 있다.
아래는 Navigatiion Guard를 이용하여 로그인 확인, 페이지 권한 확인하는 예제이다.

// router.js
const router = new Router({
    routes: [
        {
            path: '/',
            name: 'HelloWorld',
            component: HelloWorld,
            meta: {
                isLogged: true,
                roles: ['Admin']
            }
        }
    ]
})

// router guard
router.beforeEach((to, from, next) => {
    let isLogged = ...
    // /login URL은 로그인 페이지
    to.meta.isLogged && !isLogged ? next({ path: '/login', replace: true }) : next()
})

// router guard
router.beforeEach((to, from, next) => {
    let role = ...
    // /403 URL은 403 페이지
    to.meta.roles && !to.meta.roles.includes(role) ? next({ path: '/403', replace: true }) : next()
})
반응형