From 45ecb205920be60c9b454dbb55cf4fe213bbc697 Mon Sep 17 00:00:00 2001 From: Ben Hong Date: Thu, 11 Mar 2021 10:17:10 -0500 Subject: [PATCH] fix(guards): ensure beforeRouteUpdate works with aliases (#819) fix #805 --- __tests__/guards/beforeRouteUpdate.spec.ts | 13 +++++++++++++ src/router.ts | 12 +++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/__tests__/guards/beforeRouteUpdate.spec.ts b/__tests__/guards/beforeRouteUpdate.spec.ts index 2b539b6eb..5d98f21e5 100644 --- a/__tests__/guards/beforeRouteUpdate.spec.ts +++ b/__tests__/guards/beforeRouteUpdate.spec.ts @@ -11,6 +11,7 @@ const routes: RouteRecordRaw[] = [ { path: '/foo', component: Foo }, { path: '/guard/:go', + alias: '/guard-alias/:go', component: { ...Foo, beforeRouteUpdate, @@ -39,6 +40,18 @@ describe('beforeRouteUpdate', () => { expect(beforeRouteUpdate).toHaveBeenCalledTimes(1) }) + it('calls beforeRouteUpdate guards when changing params with alias', async () => { + const router = createRouter({ routes }) + beforeRouteUpdate.mockImplementationOnce(noGuard) + await router.push('/guard/valid') + // not called on initial navigation + expect(beforeRouteUpdate).not.toHaveBeenCalled() + // simulate a mounted route component + router.currentRoute.value.matched[0].instances.default = {} as any + await router.push('/guard-alias/other') + expect(beforeRouteUpdate).toHaveBeenCalledTimes(1) + }) + it('does not call beforeRouteUpdate guard if the view is not mounted', async () => { const router = createRouter({ routes }) beforeRouteUpdate.mockImplementationOnce(noGuard) diff --git a/src/router.ts b/src/router.ts index fc5946da3..d445c3849 100644 --- a/src/router.ts +++ b/src/router.ts @@ -51,7 +51,12 @@ import { computed, } from 'vue' import { RouteRecord, RouteRecordNormalized } from './matcher/types' -import { parseURL, stringifyURL, isSameRouteLocation } from './location' +import { + parseURL, + stringifyURL, + isSameRouteLocation, + isSameRouteRecord, +} from './location' import { extractComponentsGuards, guardToPromiseFn } from './navigationGuards' import { warn } from './warning' import { RouterLink } from './RouterLink' @@ -1162,8 +1167,9 @@ function extractChangingRecords( for (let i = 0; i < len; i++) { const recordFrom = from.matched[i] if (recordFrom) { - if (to.matched.indexOf(recordFrom) < 0) leavingRecords.push(recordFrom) - else updatingRecords.push(recordFrom) + if (to.matched.find(isSameRouteRecord.bind(null, recordFrom))) + updatingRecords.push(recordFrom) + else leavingRecords.push(recordFrom) } const recordTo = to.matched[i] if (recordTo) {