Skip to content

Commit 665f3b0

Browse files
buqiyuanbrc-dd
andauthored
feat(client): add onBeforePageLoad hook for router (#2564)
Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
1 parent fa3780f commit 665f3b0

File tree

2 files changed

+41
-4
lines changed

2 files changed

+41
-4
lines changed

docs/reference/runtime-api.md

+20-1
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,27 @@ Returns the VitePress router instance so you can programmatically navigate to an
8686

8787
```ts
8888
interface Router {
89+
/**
90+
* Current route.
91+
*/
8992
route: Route
90-
go: (href?: string) => Promise<void>
93+
/**
94+
* Navigate to a new URL.
95+
*/
96+
go: (to?: string) => Promise<void>
97+
/**
98+
* Called before the route changes. Return `false` to cancel the navigation.
99+
*/
100+
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
101+
/**
102+
* Called before the page component is loaded (after the history state is
103+
* updated). Return `false` to cancel the navigation.
104+
*/
105+
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
106+
/**
107+
* Called after the route changes.
108+
*/
109+
onAfterRouteChanged?: (to: string) => Awaitable<void>
91110
}
92111
```
93112

src/client/app/router.ts

+21-3
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,26 @@ export interface Route {
1212
}
1313

1414
export interface Router {
15+
/**
16+
* Current route.
17+
*/
1518
route: Route
16-
go: (href?: string) => Promise<void>
17-
onBeforeRouteChange?: (to: string) => Awaitable<void>
19+
/**
20+
* Navigate to a new URL.
21+
*/
22+
go: (to?: string) => Promise<void>
23+
/**
24+
* Called before the route changes. Return `false` to cancel the navigation.
25+
*/
26+
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
27+
/**
28+
* Called before the page component is loaded (after the history state is
29+
* updated). Return `false` to cancel the navigation.
30+
*/
31+
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
32+
/**
33+
* Called after the route changes.
34+
*/
1835
onAfterRouteChanged?: (to: string) => Awaitable<void>
1936
}
2037

@@ -47,7 +64,7 @@ export function createRouter(
4764
}
4865

4966
async function go(href: string = inBrowser ? location.href : '/') {
50-
await router.onBeforeRouteChange?.(href)
67+
if ((await router.onBeforeRouteChange?.(href)) === false) return
5168
const url = new URL(href, fakeHost)
5269
if (!siteDataRef.value.cleanUrls) {
5370
// ensure correct deep link so page refresh lands on correct files.
@@ -62,6 +79,7 @@ export function createRouter(
6279
history.replaceState({ scrollPosition: window.scrollY }, document.title)
6380
history.pushState(null, '', href)
6481
}
82+
if ((await router.onBeforePageLoad?.(href)) === false) return
6583
await loadPage(href)
6684
await router.onAfterRouteChanged?.(href)
6785
}

0 commit comments

Comments
 (0)