Skip to content

Hooks

Hooks offer a way to register callbacks on router lifecycle events.

ts
onAfterRouteEnter: (to, context) => {
   ...
}

Lifecycle

Before Hooks

  • onBeforeRouteEnter: Triggered before a route gets mounted.
  • onBeforeRouteUpdate: Triggered before a route changes. Specifically when the route changed but that parent or child didn’t.
  • onBeforeRouteLeave: Triggered before a route is about to be unmounted

After Hooks

  • onAfterRouteLeave: Triggered after a route gets unmounted.
  • onAfterRouteUpdate: Triggered after a route changes. Specifically when the route changed but that parent or child didn’t.
  • onAfterRouteEnter: Triggered after a route is mounted

Context

The router provides to and a context argument to your hook callback. The context will always include:

PropertyDescription
fromWhat was the route prior to the hook's execution
pushConvenient way to move the user from wherever they were to a new route.
replaceSame as push, but with options: { replace: true }.
rejectTrigger a rejection for the router to handle

See AfterRouteHookContext

If the hooks lifecycle is a before hook, you'll also have access to the following property in your context:

PropertyDescription
abortStops the router from continuing with route change

See BeforeRouteHookContext

Levels

Hooks can be registered globally, on your route, or from within a component. This is useful for both providing the most convenient dx, but also can be a useful tool for ensuring proper execution order of your business logic.

Execution Order

  1. Global hooks
  2. Route hooks
  3. Component Hooks

Global

ts
router.onAfterRouteEnter((to, context) => {
  ...
})

Route

ts
createRoute({
  name: 'Home',
  onAfterRouteEnter: (to, context) => {
    ...
  }
})

Component

In order to register a hook from within a component, you must use the composition API.

ts
import { onBeforeRouteLeave } from '@kitbag/router'

onAfterRouteEnter((to, context) => {
  ...
})

WARNING

You cannot register onBeforeRouteEnter or onAfterRouteEnter hooks from within a component, since the component must have been mounted to discover the hook.

Global Injection

Hooks are run within the context of the Vue app the router is installed. This means you can use vue's inject function to access global values.

ts
import { inject } from 'vue'

router.onAfterRouteEnter(() => {
  const value = inject('global')

  ...
})