Skip to content

Routes

Routes are used to define the structure of your application and to provide a way to navigate between different parts of your application or to an external address. You can define routes within your application using the createRoute function.

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

const home = createRoute({
  name: 'home',
  path: '/',
})

Name

The name property is used to identify the route. Each route mush have a unique name.

ts
const home = createRoute({
  name: 'home',
  path: '/',
})

Routes without names

The name property is optional, but a route without a name cannot be navigated to. It can be useful to have unnamed routes for organizing related routes under a shared unnamed parent. Even though the parent can't be navigated to, this still ensures

  • the parents properties are merged with the child (path, query, meta, and hash)
  • any hooks defined on the parent run when the child is matched
  • the parents state is merged with the child

Path

The path property is used to define the pathname part of the route's url.

ts
const home = createRoute({
  name: 'home',
  path: '/',
})

Query

The query property is used to define the search part of the route's url. If a query is provided, a url must include a search string that matches the query.

ts
const homeAddCampaign = createRoute({
  name: 'home.black-friday',
  path: '/',
  query: {
    campaign: 'black-friday',
  },
})

Hash

The hash property is used to define the hash part of the route's url. If a hash is provided, a url's hash must match exactly.

ts
const contact = createRoute({
  name: 'home.contact',
  path: '/',
  hash: 'contact',
})

Parent

The parent property is used to create nested routes. In this example, blogPost route's path is combined with the blog route's path to form the full url. A route inherits many of its parent's properties. Specifically, path, query, meta, state, context, and hash are all combined.

ts
const blog = createRoute({
  name: 'blog',
  path: '/blog',
})

const blogPost = createRoute({
  parent: blog,
  name: 'blogPost',
  path: '/:postId',
})

Views

Use the chainable addView method to define which component(s) render when the route is active. Call it once for a single view, or chain it to register multiple views. If no view is added, a RouterView is rendered by default.

ts
import HomeView from './components/HomeView.vue'

const home = createRoute({
  name: 'home',
  path: '/',
})
.addView(HomeView)

Options

Everything else about a view is passed in an options object as the second argument.

OptionDescription
nameRegisters the view as a named view. Defaults to the unnamed view.
propsA getter for the props bound to the component. Required when the component has required props.
prefetchWhat assets are prefetched for this view. Overrides the route's config for this view only.

Named Views

Pass a name to register a named view. A route can mix a default view with named views.

ts
import HomeView from './components/HomeView.vue'
import HomeSidebar from './components/HomeSidebar.vue'

const home = createRoute({
  name: 'home',
  path: '/',
})
.addView(HomeView)
.addView(HomeSidebar, {
  name: 'sidebar',
})

Props

Pass a props getter to bind props to the view's component. It's a callback that returns an object (or a promise of one); everything returned is bound to the component. See Component Props for more details.

ts
import UserView from './components/UserView.vue'

const user = createRoute({
  name: 'user',
  path: '/user/[id]',
})
.addView(UserView, {
  props: (route) => ({ userId: route.params.id }),
})

The getter is required when the component has required props, and optional otherwise.

Arguments

The props callback receives two arguments:

ArgumentDescription
routeThe resolved route, including any params. See Params for more details.
contextAn object with helper methods for navigation (push, replace, reject, update) and the parent route's props. See PropsCallbackContext for more details.

Return Type

The props callback must return an object or a promise that resolves to an object. The object must satisfy the props for the component. If the component has required props, TypeScript will error until the getter returns a matching object.

Prefetch

Pass a prefetch config to control what is prefetched for that view. It overrides the route's config for this view only, which is useful when a route has multiple views and only some are worth prefetching. See Prefetching for more details.

ts
const home = createRoute({
  name: 'home',
  path: '/',
})
.addView(HomeView, {
  prefetch: false,
})
.addView(HomeSidebar, {
  name: 'sidebar',
  prefetch: 'eager',
})

Component

WARNING

The component property is deprecated. Use addView instead.

The component property is used to define the component that will be rendered when the route is active.

ts
import HomeView from './components/HomeView.vue'

const home = createRoute({
  name: 'home',
  path: '/',
  component: HomeView,
})

Components

WARNING

The components property is deprecated. Use addView with named views instead.

The components property is used to define multiple components for named views.

ts
import HomeView from './components/HomeView.vue'
import HomeSidebar from './components/HomeSidebar.vue'

const home = createRoute({
  name: 'home',
  path: '/',
  components: {
    default: HomeView,
    sidebar: HomeSidebar,
  },
})

Props

WARNING

The props argument is deprecated. Pass the props getter to addView instead.

The props argument is used to provide props for route components. It must be a callback function that returns an object. Everything returned from the callback will be bound to the component.

ts
import HomeView from './components/HomeView.vue'

const home = createRoute({
  name: 'home',
  path: '/',
  component: HomeView,
}, () => ({ userId: 1 }))

Meta

The meta property is used to define metadata for the route. Meta is optional and can be used to define static metadata for the route to reference in the router route or in hooks

ts
import HomeView from './components/HomeView.vue'

const home = createRoute({
  name: 'home',
  path: '/',
  meta: {
    title: 'Home',
  },
})
.addView(HomeView)

State

The state property is used to define optional data that can stored on the route in the browser's history. State is always optional, but it can be used to pass data to the route when navigating or to preserve state when navigating away from the route.

ts
import ContactView from './components/HomeView.vue'

const contact = createRoute({
  name: 'contact',
  path: '/',
  state: {
    firstName: String,
    lastName: String,
    message: String,
  },
})
.addView(ContactView)

Hooks

Hooks can be defined for a individual route. See Hooks for more information about hooks.

ts
import HomeView from './components/HomeView.vue'

const home = createRoute({
  name: 'home',
  path: '/',
})
.addView(HomeView)

home.onBeforeRouteEnter(() => {
  console.log('before route enter')
})

Title

The setTitle callback is used to set the document title for the route. The callback is given the resolved route and a context object. The callback can be async, and should return a string that should be set as the document.title.

The context object has the following properties:

PropertyDescription
fromWhat was the route prior to the hook's execution
getParentTitleA function that returns the title of the parent route.
ts
import { createRoute } from '@kitbag/router'

const user = createRoute({
  name: 'user.profile',
  path: '/user/:userId',
})

user.setTitle((to, context) => {
  const user = userStore.getUser(to.params.userId)
  return `Profile: ${user.name}`
})

INFO

There is also a setTitle callback on rejections.

Context

The context for a route is the collection of routes and rejections that are associated with the route. The context you provide to this route will be available to the hooks and props callback functions for this route.

ts
const newHomePage = createRoute({
  name: 'new-home',
  path: '/',
})
.addView(NewHomePage)

const home = createRoute({
  name: 'home',
  path: '/',
  context: [newHomePage],
})

home.onBeforeRouteEnter((to, { replace }) => {
  if(user.isCanary) {
    // TS knows about 'new-home' because it's in the context
    replace('new-home')
  }
})

Prefetching

Routes can be prefetched to improve performance. See the Prefetching documentation for more information.

ts
const home = createRoute({
  name: 'home',
  path: '/',
  prefetch: {
    components: 'lazy',
    props: 'intent'
  },
})

Hoisting

When the hoist property is true, the route will be treated as a root route. This allows you to leverage the component nesting without having to use a nested URL.

ts
const parentRoute = createRoute({
  name: 'parent',
  path: '/parent',
})

const regularChildRoute = createRoute({
  parent: parentRoute,
  name: 'parent.regular',
  path: '/regular',
})

const hoistedExample = createRoute({
  parent: parentRoute,
  name: 'parent.nested',
  path: '/nested',
  hoist: true,
})

regularChildRoute.stringify() 
// ^ "/parent/regular"
hoistedExample.string()
// ^ "/nested"