From: Eduardo San Martin Morote Date: Wed, 22 Apr 2020 13:11:50 +0000 (+0200) Subject: feat(router): add beforeResolve X-Git-Tag: v4.0.0-alpha.8~53 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=9697134c05f0f4c6fde48a773880946074e95666;p=thirdparty%2Fvuejs%2Frouter.git feat(router): add beforeResolve --- diff --git a/__tests__/guards/beforeResolve.spec.ts b/__tests__/guards/beforeResolve.spec.ts new file mode 100644 index 00000000..a0dbeaed --- /dev/null +++ b/__tests__/guards/beforeResolve.spec.ts @@ -0,0 +1,25 @@ +import { createDom, noGuard, newRouter as createRouter } from '../utils' +import { RouteRecordRaw } from '../../src/types' + +const Home = { template: `
Home
` } +const Foo = { template: `
Foo
` } + +const routes: RouteRecordRaw[] = [ + { path: '/', component: Home }, + { path: '/foo', component: Foo }, +] + +describe('router.beforeEach', () => { + beforeAll(() => { + createDom() + }) + + it('calls beforeEach guards on navigation', async () => { + const spy = jest.fn() + const router = createRouter({ routes }) + router.beforeResolve(spy) + spy.mockImplementationOnce(noGuard) + await router.push('/foo') + expect(spy).toHaveBeenCalledTimes(1) + }) +}) diff --git a/src/router.ts b/src/router.ts index 0bce78a4..cb10805b 100644 --- a/src/router.ts +++ b/src/router.ts @@ -147,6 +147,7 @@ export interface Router { go(distance: number): void beforeEach(guard: NavigationGuardWithThis): () => void + beforeResolve(guard: NavigationGuardWithThis): () => void afterEach(guard: PostNavigationGuard): () => void onError(handler: ErrorHandler): () => void @@ -170,6 +171,7 @@ export function createRouter({ const matcher = createRouterMatcher(routes, {}) const beforeGuards = useCallbacks>() + const beforeResolveGuards = useCallbacks>() const afterGuards = useCallbacks() const currentRoute = ref( START_LOCATION_NORMALIZED @@ -452,6 +454,14 @@ export function createRouter({ // run the queue of per route beforeEnter guards await runGuardQueue(guards) + + // check global guards beforeEach + guards = [] + for (const guard of beforeResolveGuards.list()) { + guards.push(guardToPromiseFn(guard, to, from)) + } + + await runGuardQueue(guards) } function triggerAfterEach( @@ -660,6 +670,7 @@ export function createRouter({ forward: () => history.go(1), beforeEach: beforeGuards.add, + beforeResolve: beforeResolveGuards.add, afterEach: afterGuards.add, onError: errorHandlers.add,