feat(client): add onBeforePageLoad hook for router (#2564)

Co-authored-by: Divyansh Singh <40380293+brc-dd@users.noreply.github.com>
pull/2573/head
bqy_fe 2 years ago committed by GitHub
parent fa3780f8ef
commit 665f3b02f8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -86,8 +86,27 @@ Returns the VitePress router instance so you can programmatically navigate to an
```ts
interface Router {
/**
* Current route.
*/
route: Route
go: (href?: string) => Promise<void>
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is
* updated). Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the route changes.
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
}
```

@ -12,9 +12,26 @@ export interface Route {
}
export interface Router {
/**
* Current route.
*/
route: Route
go: (href?: string) => Promise<void>
onBeforeRouteChange?: (to: string) => Awaitable<void>
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is
* updated). Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the route changes.
*/
onAfterRouteChanged?: (to: string) => Awaitable<void>
}
@ -47,7 +64,7 @@ export function createRouter(
}
async function go(href: string = inBrowser ? location.href : '/') {
await router.onBeforeRouteChange?.(href)
if ((await router.onBeforeRouteChange?.(href)) === false) return
const url = new URL(href, fakeHost)
if (!siteDataRef.value.cleanUrls) {
// ensure correct deep link so page refresh lands on correct files.
@ -62,6 +79,7 @@ export function createRouter(
history.replaceState({ scrollPosition: window.scrollY }, document.title)
history.pushState(null, '', href)
}
if ((await router.onBeforePageLoad?.(href)) === false) return
await loadPage(href)
await router.onAfterRouteChanged?.(href)
}

Loading…
Cancel
Save