From: Eduardo San Martin Morote Date: Thu, 6 Jul 2023 16:31:35 +0000 (+0200) Subject: fix: allow removing guards within the guard X-Git-Tag: v4.2.4~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=d60d36c49bbbd308618926ff0131890bfed2cdff;p=thirdparty%2Fvuejs%2Frouter.git fix: allow removing guards within the guard --- diff --git a/packages/router/__tests__/guards/afterEach.spec.ts b/packages/router/__tests__/guards/afterEach.spec.ts index 01a9d44f..d4200486 100644 --- a/packages/router/__tests__/guards/afterEach.spec.ts +++ b/packages/router/__tests__/guards/afterEach.spec.ts @@ -65,4 +65,16 @@ describe('router.afterEach', () => { ) expect(spy).toHaveBeenCalledTimes(2) }) + + it('removing an afterEach guard within one does not affect others', async () => { + const spy1 = jest.fn() + const spy2 = jest.fn() + const router = createRouter({ routes }) + router.afterEach(spy1) + const remove = router.afterEach(spy2) + spy1.mockImplementationOnce(remove) + await router.push('/foo') + expect(spy1).toHaveBeenCalledTimes(1) + expect(spy2).toHaveBeenCalledTimes(1) + }) }) diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index dbd426f3..43eaecfd 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -906,9 +906,9 @@ export function createRouter(options: RouterOptions): Router { ): void { // navigation is confirmed, call afterGuards // TODO: wrap with error handlers - for (const guard of afterGuards.list()) { - runWithContext(() => guard(to, from, failure)) - } + afterGuards + .list() + .forEach(guard => runWithContext(() => guard(to, from, failure))) } /** diff --git a/packages/router/src/utils/callbacks.ts b/packages/router/src/utils/callbacks.ts index 6f9f5aab..441aba81 100644 --- a/packages/router/src/utils/callbacks.ts +++ b/packages/router/src/utils/callbacks.ts @@ -18,7 +18,7 @@ export function useCallbacks() { return { add, - list: () => handlers, + list: () => handlers.slice(), reset, } }