diff --git a/packages/vue-router/__tests__/locationHistory.spec.ts b/packages/vue-router/__tests__/locationHistory.spec.ts index fe7f94e723d..196dcc75d88 100644 --- a/packages/vue-router/__tests__/locationHistory.spec.ts +++ b/packages/vue-router/__tests__/locationHistory.spec.ts @@ -84,4 +84,25 @@ describe('Location History', () => { expect(locationHistory.canGoBack(1, 0, 1)).toEqual(true); expect(locationHistory.canGoBack(2, 0, 1)).toEqual(false); }); + + it('should correctly find the last location', () => { + const [home, pageA, pageB, pageC] = [ + { pathname: '/home' }, + { pathname: '/page-a', pushedByRoute: '/home' }, + { pathname: '/page-b', pushedByRoute: '/page-a' }, + { pathname: '/page-c', pushedByRoute: '/page-b' }, + ]; + + locationHistory.add(home); + locationHistory.add(pageA); + locationHistory.add(pageB); + locationHistory.add(pageC); + + expect(locationHistory.findLastLocation(pageB)).toEqual(pageA); + expect(locationHistory.findLastLocation(pageB, -2)).toEqual(home); + + expect(locationHistory.findLastLocation(pageC)).toEqual(pageB); + expect(locationHistory.findLastLocation(pageC, -2)).toEqual(pageA); + expect(locationHistory.findLastLocation(pageC, -3)).toEqual(home); + }); }); diff --git a/packages/vue-router/src/locationHistory.ts b/packages/vue-router/src/locationHistory.ts index f48499254ea..9e12afd799a 100644 --- a/packages/vue-router/src/locationHistory.ts +++ b/packages/vue-router/src/locationHistory.ts @@ -239,15 +239,11 @@ export const createLocationHistory = () => { } } } - if (delta < -1) { - return locationHistory[locationHistory.length - 1 + delta]; - } else { - for (let i = locationHistory.length - 2; i >= 0; i--) { - const ri = locationHistory[i]; - if (ri) { - if (ri.pathname === routeInfo.pushedByRoute) { - return ri; - } + for (let i = locationHistory.length - 2; i >= 0; i--) { + const ri = locationHistory[i]; + if (ri) { + if (ri.pathname === routeInfo.pushedByRoute) { + return locationHistory[i + 1 + delta] } } }