FrameWorks/Vue

VueRouter의 Router Meta Field 파헤치기

ABCD 2024. 6. 27.

route's meta field

라우트에 meta라는 속성 객체를 사용하여 임의의 정보를 추가하면, route location과 navigation guard에서 접근할 수 있습니다.

const routes = [
    {
        path: '/posts',
        component: PostsLayout,
        children: [
            {
                path: 'new',
                component: PostsNew,
                // only authenticated users can create posts
                meta: { requiresAuth: true },
            },
            {
                path: ':id',
                component: PostsDetail,
                // anybody can read a post
                meta: { requiresAuth: false },
            },
        ],
    },
]

자! 그럼 접근을 할. 수. 있. 다. 라는것을 알았습니다.

그러면 어떻게 접근해야 할까요??

우선 routes의 각 라우트 객체를 라우트 레코드(route record)라고 하며, 중첩될 수 있습니다. 따라서, 매칭된 라우트는 둘 이상의 라우트 레코드와 매칭될 수 있습니다.

예를 들어 위에 두성된 라우트에서 /posts/new에 접근했다고 가정해 봅시다. 그러면 부모 라우트 레코드(posts)와 자식 라우트 레코드(new)와 모두 일치합니다.

모든 라우트에 의해 일치된 라우트 기록은 route객체에 route.matched에 배열로 노출되게 됩니다. meta의 경우 해당 배열을 순회하여 찾아내도 되지만, VueRouter에는 부모~자식간의 meta필드의 비재귀적 병합인 route.meta를 제공합니다.

이 말은 즉, 부모와 자식에 작성한 meta 필드 정보를 route.meta를 통해 전부 꺼낼 수 있다는 말이 됩니다.

 

예를 들어보겠습니다.

const routes = [  
    {  
        path: '/router/:route',  
        name: 'router',  
        props: {  
            routeObject: {  
                a: 0,  
                b: '',  
                c: true,  
            },  
            route: true,  
        },  
        meta: { test1: true },  
        component: () => import('@/components/RouterStudy.vue'),  
        children: [{ path: '', name: 'routerNote', meta: { test2: false }, component: () => import('@/components/Note.vue'), props: true }],  
    },  
]  

router.afterEach((to, from, failure) => {
    let route = useRoute()
    console.log(route.meta)  
    console.log(to)
})
// console.log(route.meta)
{test1: true, test2: false}
// console.log(to)
fullPath: "/router/%EB%9D%BC%EC%9A%B0%ED%8A%B8"
hash: ""
href: "/router/%EB%9D%BC%EC%9A%B0%ED%8A%B8"
matched: (2) [{…}, {…}]
meta: {test1: true, test2: false}
name: "routerNote"
params: {route: '라우트'}
path: "/router/%EB%9D%BC%EC%9A%B0%ED%8A%B8"
query: {}
redirectedFrom: undefined
...
728x90
반응형

댓글

💲 추천 글