diff --git a/packages/router/__tests__/matcher/addingRemoving.spec.ts b/packages/router/__tests__/matcher/addingRemoving.spec.ts index 5c48b8676..85ef37888 100644 --- a/packages/router/__tests__/matcher/addingRemoving.spec.ts +++ b/packages/router/__tests__/matcher/addingRemoving.spec.ts @@ -16,6 +16,21 @@ describe('Matcher: adding and removing records', () => { }) }) + it('can remove all records', () => { + const matcher = createRouterMatcher([], {}) + matcher.addRoute({ path: '/', component }) + matcher.addRoute({ path: '/about', component, name: 'about' }) + matcher.addRoute({ + path: '/with-children', + component, + children: [{ path: 'child', component }], + }) + expect(matcher.getRoutes()).not.toHaveLength(0) + matcher.clearRoutes() + expect(matcher.getRoutes()).toHaveLength(0) + expect(matcher.getRecordMatcher('about')).toBeFalsy() + }) + it('throws when adding *', () => { const matcher = createRouterMatcher([], {}) expect(() => { diff --git a/packages/router/src/matcher/index.ts b/packages/router/src/matcher/index.ts index fc88dacad..0d67061d3 100644 --- a/packages/router/src/matcher/index.ts +++ b/packages/router/src/matcher/index.ts @@ -27,10 +27,9 @@ import type { RouteRecordNameGeneric, _RouteRecordProps } from '../typed-routes' */ export interface RouterMatcher { addRoute: (record: RouteRecordRaw, parent?: RouteRecordMatcher) => () => void - removeRoute(matcher: RouteRecordMatcher): void removeRoute(name: NonNullable): void - + clearRoutes: () => void getRoutes: () => RouteRecordMatcher[] getRecordMatcher: ( name: NonNullable @@ -345,7 +344,19 @@ export function createRouterMatcher( // add initial routes routes.forEach(route => addRoute(route)) - return { addRoute, resolve, removeRoute, getRoutes, getRecordMatcher } + function clearRoutes() { + matchers.length = 0 + matcherMap.clear() + } + + return { + addRoute, + resolve, + removeRoute, + clearRoutes, + getRoutes, + getRecordMatcher, + } } function paramsFromLocation( diff --git a/packages/router/src/router.ts b/packages/router/src/router.ts index 20df891ab..da33e976d 100644 --- a/packages/router/src/router.ts +++ b/packages/router/src/router.ts @@ -239,6 +239,11 @@ export interface Router { */ getRoutes(): RouteRecord[] + /** + * Delete all routes from the router matcher. + */ + clearRoutes(): void + /** * Returns the {@link RouteLocation | normalized version} of a * {@link RouteLocationRaw | route location}. Also includes an `href` property @@ -1228,6 +1233,7 @@ export function createRouter(options: RouterOptions): Router { addRoute, removeRoute, + clearRoutes: matcher.clearRoutes, hasRoute, getRoutes, resolve,