From: Ben Hong Date: Thu, 11 Mar 2021 15:17:10 +0000 (-0500) Subject: fix(guards): ensure beforeRouteUpdate works with aliases (#819) X-Git-Tag: v4.0.5~3 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=45ecb205920be60c9b454dbb55cf4fe213bbc697;p=thirdparty%2Fvuejs%2Frouter.git fix(guards): ensure beforeRouteUpdate works with aliases (#819) fix #805 --- diff --git a/__tests__/guards/beforeRouteUpdate.spec.ts b/__tests__/guards/beforeRouteUpdate.spec.ts index 2b539b6e..5d98f21e 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 fc5946da..d445c384 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) {