]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix: keep optional params coming from a parent record (#2031)
authorchuyuan du <chuyuandu@163.com>
Tue, 13 Feb 2024 16:10:28 +0000 (00:10 +0800)
committerGitHub <noreply@github.com>
Tue, 13 Feb 2024 16:10:28 +0000 (17:10 +0100)
* keep optional params coming from a parent record when resolving a location

* format code

* improve code logic and  add unit test for parent optional params

* revert wrong commit of pnpm-lock.yaml

packages/router/__tests__/matcher/resolve.spec.ts
packages/router/src/matcher/index.ts

index 359a3daa93b89da871ee413ce6df4759a8ea79ce..de00849e13c001f800b480bed6801e062d1530e2 100644 (file)
@@ -777,6 +777,40 @@ describe('RouterMatcher.resolve', () => {
       )
     })
 
+    it('keep optional params from parent record', () => {
+      const Child_A = { path: 'a', name: 'child_a', components }
+      const Child_B = { path: 'b', name: 'child_b', components }
+      const Parent = {
+        path: '/:optional?/parent',
+        name: 'parent',
+        components,
+        children: [Child_A, Child_B],
+      }
+      assertRecordMatch(
+        Parent,
+        { name: 'child_b' },
+        {
+          name: 'child_b',
+          path: '/foo/parent/b',
+          params: { optional: 'foo' },
+          matched: [
+            Parent as any,
+            {
+              ...Child_B,
+              path: `${Parent.path}/${Child_B.path}`,
+            },
+          ],
+        },
+        {
+          params: { optional: 'foo' },
+          path: '/foo/parent/a',
+          matched: [],
+          meta: {},
+          name: undefined,
+        }
+      )
+    })
+
     it('discards non existent params', () => {
       assertRecordMatch(
         { path: '/', name: 'home', components },
index 39a3c24b11c4d80dce72f85479cc15f6238a08dd..bdc292c86b251ee3d781fe372ca8af1a2c68018c 100644 (file)
@@ -277,8 +277,13 @@ export function createRouterMatcher(
         paramsFromLocation(
           currentLocation.params,
           // only keep params that exist in the resolved location
-          // TODO: only keep optional params coming from a parent record
-          matcher.keys.filter(k => !k.optional).map(k => k.name)
+          // only keep optional params coming from a parent record
+          matcher.keys
+            .filter(k => !k.optional)
+            .concat(
+              matcher.parent ? matcher.parent.keys.filter(k => k.optional) : []
+            )
+            .map(k => k.name)
         ),
         // discard any existing params in the current location that do not exist here
         // #1497 this ensures better active/exact matching