From: Eduardo San Martin Morote Date: Tue, 14 Apr 2020 09:19:10 +0000 (+0200) Subject: feat: merge meta fields X-Git-Tag: v4.0.0-alpha.6~27 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=72a052fdf4a198e3ac72779f1b7b8b80d0ac018d;p=thirdparty%2Fvuejs%2Frouter.git feat: merge meta fields --- diff --git a/__tests__/router.spec.ts b/__tests__/router.spec.ts index 51057338..22f06fe6 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 d9da0168..1d57d07f 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 }