docs: explain router route-change handlers (#5253)

pull/5256/head
T 2 weeks ago committed by GitHub
parent 01822e7b44
commit 8e38b1069b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -67,6 +67,24 @@ export default {
}
```
The `router` value is the same VitePress router instance returned by [`useRouter()`](../reference/runtime-api#userouter). To listen for route changes, assign handlers on the router:
```ts [.vitepress/theme/index.ts]
export default {
enhanceApp({ router }) {
router.onBeforeRouteChange = (to) => {
console.log('navigating to', to)
}
router.onAfterRouteChange = (to) => {
console.log('navigated to', to)
}
}
}
```
Return `false` from `onBeforeRouteChange` or `onBeforePageLoad` to cancel navigation.
The default export is the only contract for a custom theme, and only the `Layout` property is required. So technically, a VitePress theme can be as simple as a single Vue component.
Inside your layout component, it works just like a normal Vite + Vue 3 application. Do note the theme also needs to be [SSR-compatible](./ssr-compat).

@ -124,6 +124,18 @@ interface Router {
}
```
Assign route-change handlers on the router instance:
```ts
const router = useRouter()
router.onBeforeRouteChange = (to) => {
console.log('navigating to', to)
}
```
For custom themes, the same router is available from [`enhanceApp`](../guide/custom-theme#theme-interface).
## `withBase` <Badge type="info" text="helper" />
- **Type**: `(path: string) => string`

Loading…
Cancel
Save