Vue-router 라우트 메타 필드

YEZI🎐·2022년 12월 9일
0

Vue

목록 보기
34/45

라우트 메타 필드

라우트를 정의 할 때 meta 필드를 포함시킬 수 있다.

const router = new VueRouter({
  routes: [
    {	// 라우트 레코드 01
      path: '/foo',
      component: Foo,
      children: [
        {	// 라우트 레코드 02
          path: 'bar',
          component: Bar,
          // 메타 필드
          meta: { requiresAuth: true }
        }	// 라우트 레코드 02
      ]
    }	// 라우트 레코드 01
  ]
})

routes 설정의 각 라우트 객체를 라우트 레코드 라고 한다.
라우트 레코드는 중첩 될 수 있으며 라우트가 일치하면(ex. /foo/bar) 둘 이상의 라우트 레코드와 잠재적으로 일치한다.
예를 들어, 위 라우트 구성에서 URL /foo/bar는 상위 라우트 레코드와 하위 라우트 레코드 모두 일치한다.

라우트와 일치하는 모든 라우트 레코드는 $route 객체(네비게이션 가드의 라우트 객체)에서 $route.matched 배열이 된다.
그러므로 $route.matched를 반복하여 라우트 레코드의 메타 필드를 검사 할 필요가 있다.

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 이 라우트는 인증이 필요하며 로그인 한 경우를 체크해야함
    // 그렇지 않은 경우 로그인 페이지로 리디렉션함
    if (!auth.loggedIn()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    next() // next() 반드시 호출
  }
})
profile
까먹지마도토도토잠보🐘

0개의 댓글