diff --git a/__tests__/router.spec.ts b/__tests__/router.spec.ts index 51057338c..22f06fe64 100644 --- a/__tests__/router.spec.ts +++ b/__tests__/router.spec.ts @@ -27,6 +27,14 @@ const routes: RouteRecordRaw[] = [ { path: '/repeat/:r+', name: 'repeat', component: components.Bar }, { path: '/to-p/:p', redirect: to => `/p/${to.params.p}` }, { path: '/before-leave', component: components.BeforeLeave }, + { + path: '/parent', + meta: { fromParent: 'foo' }, + component: components.Foo, + children: [ + { path: 'child', meta: { fromChild: 'bar' }, component: components.Foo }, + ], + }, { path: '/inc-query-hash', redirect: to => ({ @@ -125,6 +133,16 @@ describe('Router', () => { expect(stringifyQuery).toHaveBeenCalledWith({ foo: 'bar' }) }) + it('merges meta properties from parent to child', async () => { + const { router } = await newRouter() + expect(router.resolve('/parent')).toMatchObject({ + meta: { fromParent: 'foo' }, + }) + expect(router.resolve('/parent/child')).toMatchObject({ + meta: { fromParent: 'foo', fromChild: 'bar' }, + }) + }) + it('can do initial navigation to /', async () => { const router = createRouter({ history: createMemoryHistory(), diff --git a/src/matcher/index.ts b/src/matcher/index.ts index d9da01683..1d57d07f3 100644 --- a/src/matcher/index.ts +++ b/src/matcher/index.ts @@ -246,7 +246,7 @@ export function createRouterMatcher( path, params, matched, - meta: matcher ? matcher.record.meta : {}, + meta: mergeMetaFields(matched), } } @@ -306,4 +306,19 @@ function isAliasRecord(record: RouteRecordMatcher | undefined): boolean { return false } +/** + * Merge meta fields of an array of records + * + * @param matched array of matched records + */ +function mergeMetaFields(matched: MatcherLocation['matched']) { + return matched.reduce( + (meta, record) => ({ + ...meta, + ...record.meta, + }), + {} as MatcherLocation['meta'] + ) +} + export { PathParserOptions }