API Reference

<router-link> Props

to

  • Type: RouteLocationRaw

  • Details:

    Denotes the target route of the link. When clicked, the value of the to prop will be passed to router.push() internally, so it can either be a string or a route location object.

  1. <!-- literal string -->
  2. <router-link to="/home">Home</router-link>
  3. <!-- renders to -->
  4. <a href="/home">Home</a>
  5. <!-- javascript expression using `v-bind` -->
  6. <router-link :to="'/home'">Home</router-link>
  7. <!-- same as above -->
  8. <router-link :to="{ path: '/home' }">Home</router-link>
  9. <!-- named route -->
  10. <router-link :to="{ name: 'user', params: { userId: '123' }}">User</router-link>
  11. <!-- with query, resulting in `/register?plan=private` -->
  12. <router-link :to="{ path: '/register', query: { plan: 'private' }}">
  13. Register
  14. </router-link>

replace

  • Type: boolean

  • Default: false

  • Details:

    Setting replace prop will call router.replace() instead of router.push() when clicked, so the navigation will not leave a history record.

  1. <router-link to="/abc" replace></router-link>

active-class

  • Type: string

  • Default: "router-link-active" (or global linkActiveClass)

  • Details:

    Class to apply on the rendered <a> when the link is active.

aria-current-value

  • Type: 'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false' (string)

  • Default: "page"

  • Details:

    Value passed to the attribute aria-current when the link is exactly active.

custom

  • Type: boolean

  • Default: false

  • Details:

    Whether <router-link> should not wrap its content in an <a> element. Useful when using v-slot to create a custom RouterLink. By default, <router-link> will render its content wrapped in an <a> element, even when using v-slot. Passing the custom prop, removes that behavior.

  • Examples:

    1. <router-link to="/home" custom v-slot="{ navigate, href, route }">
    2. <a :href="href" @click="navigate">{{ route.fullPath }}</a>
    3. </router-link>

    Renders <a href="/home">/home</a>.

    1. <router-link to="/home" v-slot="{ route }">
    2. <span>{{ route.fullPath }}</span>
    3. </router-link>

    Renders <a href="/home"><span>/home</span></a>.

exact-active-class

  • Type: string

  • Default: "router-link-exact-active" (or global linkExactActiveClass)

  • Details:

    Class to apply on the rendered <a> when the link is exact active.

<router-link>‘s v-slot

<router-link> exposes a low level customization through a scoped slot. This is a more advanced API that primarily targets library authors but can come in handy for developers as well, to build a custom component like a NavLink or other.

TIP

Remember to pass the custom option to <router-link> to prevent it from wrapping its content inside of an <a> element.

  1. <router-link
  2. to="/about"
  3. custom
  4. v-slot="{ href, route, navigate, isActive, isExactActive }"
  5. >
  6. <NavLink :active="isActive" :href="href" @click="navigate">
  7. {{ route.fullPath }}
  8. </NavLink>
  9. </router-link>
  • href: resolved url. This would be the href attribute of an <a> element. It contains the base if any was provided.
  • route: resolved normalized location.
  • navigate: function to trigger the navigation. It will automatically prevent events when necessary, the same way router-link does, e.g. ctrl or cmd + click will still be ignored by navigate.
  • isActive: true if the active class should be applied. Allows to apply an arbitrary class.
  • isExactActive: true if the exact active class should be applied. Allows to apply an arbitrary class.

Example: Applying Active Class to Outer Element

Sometimes we may want the active class to be applied to an outer element rather than the <a> element itself, in that case, you can wrap that element inside a router-link and use the v-slot properties to create your link:

  1. <router-link
  2. to="/foo"
  3. custom
  4. v-slot="{ href, route, navigate, isActive, isExactActive }"
  5. >
  6. <li
  7. :class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
  8. >
  9. <a :href="href" @click="navigate">{{ route.fullPath }}</a>
  10. </li>
  11. </router-link>

TIP

If you add a target="_blank" to your a element, you must omit the @click="navigate" handler.

<router-view> Props

name

  • Type: string

  • Default: "default"

  • Details:

    When a <router-view> has a name, it will render the component with the corresponding name in the matched route record’s components option.

  • See Also: Named Views

route

  • Type: RouteLocationNormalized

  • Details:

    A route location that has all of its component resolved (if any was lazy loaded) so it can be displayed.

<router-view>‘s v-slot

<router-view> exposes a v-slot API mainly to wrap your route components with <transition> and <keep-alive> components.

  1. <Suspense>
  2. <template #default>
  3. <router-view v-slot="{ Component, route }">
  4. <transition :name="route.meta.transition || 'fade'" mode="out-in">
  5. <keep-alive>
  6. <component
  7. :is="Component"
  8. :key="route.meta.usePathKey ? route.path : undefined"
  9. />
  10. </keep-alive>
  11. </transition>
  12. </router-view>
  13. </template>
  14. <template #fallback> Loading... </template>
  15. </Suspense>
  • Component: VNodes to be passed to a <component>‘s is prop.
  • route: resolved normalized route location.

createRouter

Creates a Router instance that can be used by a Vue app. Check the RouterOptions for a list of all the properties that can be passed.

Signature:

  1. export declare function createRouter(options: RouterOptions): Router

Parameters

ParameterTypeDescription
optionsRouterOptionsOptions to initialize the router

createWebHistory

Creates an HTML5 history. Most common history for single page applications. The application must be served through the http protocol.

Signature:

  1. export declare function createWebHistory(base?: string): RouterHistory

Parameters

ParameterTypeDescription
basestringoptional base to provide. Useful when the application is hosted inside of a folder like https://example.com/folder/

Examples

  1. createWebHistory() // No base, the app is hosted at the root of the domain `https://example.com`
  2. createWebHistory('/folder/') // gives a url of `https://example.com/folder/`

createWebHashHistory

Creates a hash history. Useful for web applications with no host (e.g. file://) or when configuring a server to handle any URL isn’t an option. Note you should use createWebHistory if SEO matters to you.

Signature:

  1. export declare function createWebHashHistory(base?: string): RouterHistory

Parameters

ParameterTypeDescription
basestringoptional base to provide. Defaults to location.pathname + location.search. If there is a <base> tag in the head, its value will be ignored in favor of this parameter but note it affects all the history.pushState() calls, meaning that if you use a <base> tag, its href value has to match this parameter (ignoring anything after the #)

Examples

  1. // at https://example.com/folder
  2. createWebHashHistory() // gives a url of `https://example.com/folder#`
  3. createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
  4. // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
  5. createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
  6. // you should avoid doing this because it changes the original url and breaks copying urls
  7. createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
  8. // at file:///usr/etc/folder/index.html
  9. // for locations with no `host`, the base is ignored
  10. createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`

createMemoryHistory

Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. If the user is not on a browser context, it’s up to them to replace that location with the starter location by either calling router.push() or router.replace().

Signature:

  1. export declare function createMemoryHistory(base?: string): RouterHistory

Parameters

ParameterTypeDescription
basestringBase applied to all urls, defaults to ‘/‘

Returns

A history object that can be passed to the router constructor

NavigationFailureType

Enumeration with all possible types for navigation failures. Can be passed to isNavigationFailure to check for specific failures. Never use any of the numerical values, always use the variables like NavigationFailureType.aborted.

Signature:

  1. export declare enum NavigationFailureType

Members

MemberValueDescription
aborted4An aborted navigation is a navigation that failed because a navigation guard returned false or called next(false)
cancelled8A cancelled navigation is a navigation that failed because a more recent navigation finished started (not necessarily finished).
duplicated16A duplicated navigation is a navigation that failed because it was initiated while already being at the exact same location.

START_LOCATION

  • Type: RouteLocationNormalized

  • Details:

    Initial route location where the router is. Can be used in navigation guards to differentiate the initial navigation.

    1. import { START_LOCATION } from 'vue-router'
    2. router.beforeEach((to, from) => {
    3. if (from === START_LOCATION) {
    4. // initial navigation
    5. }
    6. })

Composition API

onBeforeRouteLeave

Add a navigation guard that triggers whenever the component for the current location is about to be left. Similar to beforeRouteLeave but can be used in any component. The guard is removed when the component is unmounted.

Signature:

  1. export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void

Parameters

ParameterTypeDescription
leaveGuardNavigationGuardNavigation guard to add

onBeforeRouteUpdate

Add a navigation guard that triggers whenever the current location is about to be updated. Similar to beforeRouteUpdate but can be used in any component. The guard is removed when the component is unmounted.

Signature:

  1. export declare function onBeforeRouteUpdate(updateGuard: NavigationGuard): void

Parameters

ParameterTypeDescription
updateGuardNavigationGuardNavigation guard to add

useLink

Returns everything exposed by the v-slot API.

Signature:

  1. export declare function useLink(props: RouterLinkOptions): {
  2. route: ComputedRef<RouteLocationNormalized & { href: string }>,
  3. href: ComputedRef<string>,
  4. isActive: ComputedRef<boolean>,
  5. isExactActive: ComputedRef<boolean>,
  6. navigate: (event?: MouseEvent) => Promise(NavigationFailure | void),
  7. }

Parameters

ParameterTypeDescription
propsRouterLinkOptionsprops object that can be passed to <router-link>. Accepts Refs and ComputedRefs

useRoute

Returns the current route location. Equivalent to using $route inside templates. Must be called inside of setup().

Signature:

  1. export declare function useRoute(): RouteLocationNormalized

useRouter

Returns the router instance. Equivalent to using $router inside templates. Must be called inside of setup().

Signature:

  1. export declare function useRouter(): Router

TypeScript

Here are some of the interfaces and types used by Vue Router. The documentation references them to give you an idea of the existing properties in objects.

Router Properties

currentRoute

options

  • Type: RouterOptions

  • Details:

    Original options object passed to create the Router. Readonly.

Router Methods

addRoute

Add a new Route Record as the child of an existing route. If the route has a name and there is already an existing one with the same one, it removes it first.

Signature:

  1. addRoute(parentName: string | symbol, route: RouteRecordRaw): () => void

Parameters

ParameterTypeDescription
parentNamestring | symbolParent Route Record where route should be appended at
routeRouteRecordRawRoute Record to add

addRoute

Add a new route record to the router. If the route has a name and there is already an existing one with the same one, it removes it first.

Signature:

  1. addRoute(route: RouteRecordRaw): () => void

Parameters

ParameterTypeDescription
routeRouteRecordRawRoute Record to add

TIP

Note adding routes does not trigger a new navigation, meaning that the added route will not be displayed unless a new navigation is triggered.

afterEach

Add a navigation hook that is executed after every navigation. Returns a function that removes the registered hook.

Signature:

  1. afterEach(guard: NavigationHookAfter): () => void

Parameters

ParameterTypeDescription
guardNavigationHookAfternavigation hook to add

Examples

  1. router.afterEach((to, from, failure) => {
  2. if (isNavigationFailure(failure)) {
  3. console.log('failed navigation', failure)
  4. }
  5. })

back

Go back in history if possible by calling history.back(). Equivalent to router.go(-1).

Signature:

  1. back(): void

beforeEach

Add a navigation guard that executes before any navigation. Returns a function that removes the registered guard.

Signature:

  1. beforeEach(guard: NavigationGuard): () => void

Parameters

ParameterTypeDescription
guardNavigationGuardnavigation guard to add

beforeResolve

Add a navigation guard that executes before navigation is about to be resolved. At this state all component have been fetched and other navigation guards have been successful. Returns a function that removes the registered guard.

Signature:

  1. beforeResolve(guard: NavigationGuard): () => void

Parameters

ParameterTypeDescription
guardNavigationGuardnavigation guard to add

Examples

  1. router.beforeResolve(to => {
  2. if (to.meta.requiresAuth && !isAuthenticated) return false
  3. })

forward

Go forward in history if possible by calling history.forward(). Equivalent to router.go(1).

Signature:

  1. forward(): void

getRoutes

Get a full list of all the route records.

Signature:

  1. getRoutes(): RouteRecord[]

go

Allows you to move forward or backward through the history.

Signature:

  1. go(delta: number): void

Parameters

ParameterTypeDescription
deltanumberThe position in the history to which you want to move, relative to the current page

hasRoute

Checks if a route with a given name exists

Signature:

  1. hasRoute(name: string | symbol): boolean

Parameters

ParameterTypeDescription
namestring | symbolName of the route to check

isReady

Returns a Promise that resolves when the router has completed the initial navigation, which means it has resolved all async enter hooks and async components that are associated with the initial route. If the initial navigation already happened, the promise resolves immediately.This is useful in server-side rendering to ensure consistent output on both the server and the client. Note that on server side, you need to manually push the initial location while on client side, the router automatically picks it up from the URL.

Signature:

  1. isReady(): Promise<void>

onError

Adds an error handler that is called every time a non caught error happens during navigation. This includes errors thrown synchronously and asynchronously, errors returned or passed to next in any navigation guard, and errors occurred when trying to resolve an async component that is required to render a route.

Signature:

  1. onError(handler: (error: any, to: RouteLocationNormalized, from: RouteLocationNormalized) => any): () => void

Parameters

ParameterTypeDescription
handler(error: any, to: RouteLocationNormalized, from: RouteLocationNormalized) => anyerror handler to register

push

Programmatically navigate to a new URL by pushing an entry in the history stack.

Signature:

  1. push(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>

Parameters

ParameterTypeDescription
toRouteLocationRawRoute location to navigate to

removeRoute

Remove an existing route by its name.

Signature:

  1. removeRoute(name: string | symbol): void

Parameters

ParameterTypeDescription
namestring | symbolName of the route to remove

replace

Programmatically navigate to a new URL by replacing the current entry in the history stack.

Signature:

  1. replace(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>

Parameters

ParameterTypeDescription
toRouteLocationRawRoute location to navigate to

resolve

Returns the normalized version of a route location. Also includes an href property that includes any existing base.

Signature:

  1. resolve(to: RouteLocationRaw): RouteLocation & {
  2. href: string
  3. }

Parameters

ParameterTypeDescription
toRouteLocationRawRaw route location to resolve

RouterOptions

history

History implementation used by the router. Most web applications should use createWebHistory but it requires the server to be properly configured. You can also use a hash based history with createWebHashHistory that does not require any configuration on the server but isn’t handled at all by search engines and does poorly on SEO.

Signature:

  1. history: RouterHistory

Examples

  1. createRouter({
  2. history: createWebHistory(),
  3. // other options...
  4. })

linkActiveClass

Default class applied to active RouterLink. If none is provided, router-link-active will be applied.

Signature:

  1. linkActiveClass?: string

linkExactActiveClass

Default class applied to exact active RouterLink. If none is provided, router-link-exact-active will be applied.

Signature:

  1. linkExactActiveClass?: string

parseQuery

Custom implementation to parse a query. Must decode query keys and values. See its counterpart, stringifyQuery.

Signature:

  1. parseQuery?: (searchQuery: string) => Record<string, (string | null)[] | string | null>

Examples

Let’s say you want to use the package qs to parse queries, you can provide both parseQuery and stringifyQuery:

  1. import qs from 'qs'
  2. createRouter({
  3. // other options...
  4. parseQuery: qs.parse,
  5. stringifyQuery: qs.stringify,
  6. })

routes

Initial list of routes that should be added to the router.

Signature:

  1. routes: RouteRecordRaw[]

scrollBehavior

Function to control scrolling when navigating between pages. Can return a Promise to delay when the scrolling happens. See Scroll Behaviour for more details.

Signature:

  1. scrollBehavior?: RouterScrollBehavior

Examples

  1. function scrollBehavior(to, from, savedPosition) {
  2. // `to` and `from` are both route locations
  3. // `savedPosition` can be null if there isn't one
  4. }

stringifyQuery

Custom implementation to stringify a query object. Should not prepend a leading ?. Should properly encode query keys and values. parseQuery counterpart to handle query parsing.

Signature:

  1. stringifyQuery?: (
  2. query: Record<
  3. string | number,
  4. string | number | null | undefined | (string | number | null | undefined)[]
  5. >
  6. ) => string

RouteRecordRaw

Route record that can be provided by the user when adding routes via the routes option or via router.addRoute(). There are three different kind of route records:

  • Single views records: have a component option
  • Multiple views records (named views): have a components option
  • Redirect records: cannot have component or components option because a redirect record is never reached.

path

  • Type: string

  • Details:

    Path of the record. Should start with / unless the record is the child of another record. Can define parameters: /users/:id matches /users/1 as well as /users/posva.

  • See Also: Dynamic Route Matching

redirect

  • Type: RouteLocationRaw | (to: RouteLocationNormalized) => RouteLocationRaw (Optional)

  • Details:

    Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new target location. Can also be a function that receives the target route location and returns the location we should redirect to.

children

alias

  • Type: string | string[] (Optional)

  • Details:

    Aliases for the route. Allows defining extra paths that will behave like a copy of the record. This enables paths shorthands like /users/:id and /u/:id. All alias and path values must share the same params.

name

  • Type: string | symbol (Optional)

  • Details:

    Unique name for the route record.

beforeEnter

  • Type: NavigationGuard | NavigationGuard[] (Optional)

  • Details:

    Before enter guard specific to this record. Note beforeEnter has no effect if the record has a redirect property.

props

  • Type: boolean | Record<string, any> | (to: RouteLocationNormalized) => Record<string, any> (Optional)

  • Details:

    Allows passing down params as props to the component rendered by router-view. When passed to a multiple views record, it should be an object with the same keys as components or a boolean to be applied to each component. target location.

  • See Also: Passing props to Route Components

meta

TIP

If you want to use a functional component, make sure to add a displayName to it.

For example:

  1. const HomeView = () => h('div', 'HomePage')
  2. // in TypeScript, you will need to use the FunctionalComponent type
  3. HomeView.displayName = 'HomeView'
  4. const routes = [{ path: '/', component: HomeView }]

RouteRecordNormalized

Normalized version of a Route Record

aliasOf

  • Type: RouteRecordNormalized | undefined

  • Details:

    Defines if this record is the alias of another one. This property is undefined if the record is the original one.

beforeEnter

children

  • Type: Array of normalized route records

  • Details:

    Children route records of the current route. Empty array if none.

components

  • Type: Record<string, Component>

  • Details:

    Dictionary of named views, if none, contains an object with the key default.

meta

  • Type: RouteMeta

  • Details:

    Arbitrary data attached to the record.

  • See also: Meta fields

name

  • Type: string | symbol | undefined

  • Details:

    Name for the route record. undefined if none was provided.

path

  • Type: string

  • Details:

    Normalized path of the record. Includes any parent’s path.

props

  • Type: Record<string, boolean | Function | Record<string, any>>

  • Details:

    Dictionary of the props option for each named view. If none, it will contain only one property named default.

redirect

  • Type: RouteLocationRaw

  • Details:

    Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new target location.

RouteLocationRaw

User-level route location that can be passed to router.push(), redirect, and returned in Navigation Guards.

A raw location can either be a string like /users/posva#bio or an object:

  1. // these three forms are equivalent
  2. router.push('/users/posva#bio')
  3. router.push({ path: '/users/posva', hash: '#bio' })
  4. router.push({ name: 'users', params: { username: 'posva' }, hash: '#bio' })
  5. // only change the hash
  6. router.push({ hash: '#bio' })
  7. // only change query
  8. router.push({ query: { page: '2' } })
  9. // change one param
  10. router.push({ params: { username: 'jolyne' } })

Note path must be provided encoded (e.g. phantom blood becomes phantom%20blood) while params, query and hash must not, they are encoded by the router.

Raw route locations also support an extra option replace to call router.replace() instead of router.push() in navigation guards. Note this also internally calls router.replace() even when calling router.push():

  1. router.push({ hash: '#bio', replace: true })
  2. // equivalent to
  3. router.replace({ hash: '#bio' })

RouteLocation

Resolved RouteLocationRaw that can contain redirect records. Apart from that it has the same properties as RouteLocationNormalized.

RouteLocationNormalized

Normalized route location. Does not have any redirect records. In navigation guards, to and from are always of this type.

fullPath

  • Type: string

  • Details:

    Encoded URL associated to the route location. Contains path, query and hash.

hash

  • Type: string

  • Details:

    Decoded hash section of the URL. Always starts with a #. Empty string if there is no hash in the URL.

query

  • Type: Record<string, string | string[]>

  • Details:

    Dictionary of decoded query params extracted from the search section of the URL.

matched

meta

  • Type: RouteMeta

  • Details:

    Arbitrary data attached to all matched records merged (non recursively) from parent to child.

  • See also: Meta fields

name

  • Type: string | symbol | undefined | null

  • Details:

    Name for the route record. undefined if none was provided.

params

  • Type: Record<string, string | string[]>

  • Details:

    Dictionary of decoded params extracted from path.

path

  • Type: string

  • Details:

    Encoded pathname section of the URL associated to the route location.

redirectedFrom

  • Type: RouteLocation

  • Details:

    Route location we were initially trying to access before ending up on the current location when a redirect option was found or a navigation guard called next() with a route location. undefined if there was no redirection.

NavigationFailure

from

to

type

NavigationGuard

  • Arguments:

  • Details:

    Function that can be passed to control a router navigation. The next callback can be omitted if you return a value (or a Promise) instead, which is encouraged. Possible return values (and parameters for next) are:

    • undefined | void | true: validates the navigation
    • false: cancels the navigation
    • RouteLocationRaw: redirects to a different location
    • (vm: ComponentPublicInstance) => any only for beforeRouteEnter: A callback to be executed once the navigation completes. Receives the route component instance as the parameter.
  • See Also: Navigation Guards

Component Injections

Component Injected Properties

These properties are injected into every child component by calling app.use(router).

  • this.$router

    The router instance.

  • this.$route

    The current active route location. This property is read-only and its properties are immutable, but it can be watched.

Component Enabled Options

  • beforeRouteEnter
  • beforeRouteUpdate
  • beforeRouteLeave

See In Component Guards.