]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
feat: merge meta fields
authorEduardo San Martin Morote <posva13@gmail.com>
Tue, 14 Apr 2020 09:19:10 +0000 (11:19 +0200)
committerEduardo San Martin Morote <posva13@gmail.com>
Tue, 14 Apr 2020 09:19:10 +0000 (11:19 +0200)
__tests__/router.spec.ts
src/matcher/index.ts

index 51057338c58b03209eadafe3c889986079c34c57..22f06fe6499aaeacaf67ba3f0d221498338e521c 100644 (file)
@@ -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(),
index d9da01683a2d64e2a96ebd93ff7bac3ac867caf9..1d57d07f3719b576e1b3f9e1d0446d767e716904 100644 (file)
@@ -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 }