sidebar |
---|
auto |
-
Type:
RouteLocationRaw
-
Details:
Denotes the target route of the link. When clicked, the value of the
to
prop will be passed torouter.push()
internally, so it can either be astring
or a route location object.
<!-- literal string -->
<router-link to="/home">Home</router-link>
<!-- renders to -->
<a href="/home">Home</a>
<!-- javascript expression using `v-bind` -->
<router-link :to="'/home'">Home</router-link>
<!-- same as above -->
<router-link :to="{ path: '/home' }">Home</router-link>
<!-- named route -->
<router-link :to="{ name: 'user', params: { userId: '123' }}">User</router-link>
<!-- with query, resulting in `/register?plan=private` -->
<router-link :to="{ path: '/register', query: { plan: 'private' }}">
Register
</router-link>
-
Type:
boolean
-
Default:
false
-
Details:
Setting
replace
prop will callrouter.replace()
instead ofrouter.push()
when clicked, so the navigation will not leave a history record.
<router-link to="/abc" replace></router-link>
-
Type:
string
-
Default:
"router-link-active"
(or globallinkActiveClass
) -
Details:
Class to apply on the rendered
<a>
when the link is active.
-
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.
-
Type:
boolean
-
Default:
false
-
Details:
Whether
<router-link>
should not wrap its content in an<a>
element. Useful when usingv-slot
to create a custom RouterLink. By default,<router-link>
will render its content wrapped in an<a>
element, even when usingv-slot
. Passing thecustom
prop, removes that behavior. -
Examples:
<router-link to="/home" custom v-slot="{ navigate, href, route }"> <a :href="href" @click="navigate">{{ route.fullPath }}</a> </router-link>
Renders
<a href="/home">/home</a>
.<router-link to="/home" v-slot="{ route }"> <span>{{ route.fullPath }}</span> </router-link>
Renders
<a href="/home"><span>/home</span></a>
.
-
Type:
string
-
Default:
"router-link-exact-active"
(or globallinkExactActiveClass
) -
Details:
Class to apply on the rendered
<a>
when the link is exact active.
<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.
:::
<router-link
to="/about"
custom
v-slot="{ href, route, navigate, isActive, isExactActive }"
>
<NavLink :active="isActive" :href="href" @click="navigate">
{{ route.fullPath }}
</NavLink>
</router-link>
href
: resolved url. This would be thehref
attribute of an<a>
element. It contains thebase
if any was provided.route
: resolved normalized location.navigate
: function to trigger the navigation. It will automatically prevent events when necessary, the same wayrouter-link
does, e.g.ctrl
orcmd
+ click will still be ignored bynavigate
.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.
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:
<router-link
to="/foo"
custom
v-slot="{ href, route, navigate, isActive, isExactActive }"
>
<li
:class="[isActive && 'router-link-active', isExactActive && 'router-link-exact-active']"
>
<a :href="href" @click="navigate">{{ route.fullPath }}</a>
</li>
</router-link>
:::tip
If you add a target="_blank"
to your a
element, you must omit the @click="navigate"
handler.
:::
-
Type:
string
-
Default:
"default"
-
Details:
When a
<router-view>
has aname
, it will render the component with the corresponding name in the matched route record'scomponents
option. -
See Also: Named Views
-
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>
exposes a v-slot
API mainly to wrap your route components with <transition>
and <keep-alive>
components.
<router-view v-slot="{ Component, route }">
<transition :name="route.meta.transition || 'fade'" mode="out-in">
<keep-alive>
<suspense>
<template #default>
<component
:is="Component"
:key="route.meta.usePathKey ? route.path : undefined"
/>
</template>
<template #fallback> Loading... </template>
</suspense>
</keep-alive>
</transition>
</router-view>
Component
: VNodes to be passed to a<component>
'sis
prop.route
: resolved normalized route location.
Note you should be passing View components' props directly to the <component>
rather than the <router-view>
:
<router-view v-slot="{ Component, route }">
<component :is="Component" view-prop="value" />
</router-view>
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:
export declare function createRouter(options: RouterOptions): Router
Parameter | Type | Description |
---|---|---|
options | RouterOptions | Options to initialize the router |
Creates an HTML5 history. Most common history for single page applications. The application must be served through the http protocol.
Signature:
export declare function createWebHistory(base?: string): RouterHistory
Parameter | Type | Description |
---|---|---|
base | string |
optional base to provide. Useful when the application is hosted inside of a folder like https://example.com/folder/ |
createWebHistory() // No base, the app is hosted at the root of the domain `https://example.com`
createWebHistory('/folder/') // gives a url of `https://example.com/folder/`
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:
export declare function createWebHashHistory(base?: string): RouterHistory
Parameter | Type | Description |
---|---|---|
base | string |
optional 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 # ) |
// at https://example.com/folder
createWebHashHistory() // gives a url of `https://example.com/folder#`
createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
// if the `#` is provided in the base, it won't be added by `createWebHashHistory`
createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
// you should avoid doing this because it changes the original url and breaks copying urls
createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
// at file:///usr/etc/folder/index.html
// for locations with no `host`, the base is ignored
createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
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:
export declare function createMemoryHistory(base?: string): RouterHistory
Parameter | Type | Description |
---|---|---|
base | string |
Base applied to all urls, defaults to '/' |
A history object that can be passed to the router constructor
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:
export declare enum NavigationFailureType
Member | Value | Description |
---|---|---|
aborted | 4 | An aborted navigation is a navigation that failed because a navigation guard returned false or called next(false) |
cancelled | 8 | A cancelled navigation is a navigation that failed because a more recent navigation finished started (not necessarily finished). |
duplicated | 16 | A duplicated navigation is a navigation that failed because it was initiated while already being at the exact same location. |
-
Type:
RouteLocationNormalized
-
Details:
Initial route location where the router is. Can be used in navigation guards to differentiate the initial navigation.
import { START_LOCATION } from 'vue-router' router.beforeEach((to, from) => { if (from === START_LOCATION) { // initial navigation } })
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:
export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void
Parameter | Type | Description |
---|---|---|
leaveGuard | NavigationGuard |
Navigation guard to add |
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:
export declare function onBeforeRouteUpdate(updateGuard: NavigationGuard): void
Parameter | Type | Description |
---|---|---|
updateGuard | NavigationGuard |
Navigation guard to add |
Returns everything exposed by the v-slot
API.
Signature:
export declare function useLink(props: RouterLinkOptions): {
route: ComputedRef<RouteLocationNormalized & { href: string }>,
href: ComputedRef<string>,
isActive: ComputedRef<boolean>,
isExactActive: ComputedRef<boolean>,
navigate: (event?: MouseEvent) => Promise(NavigationFailure | void),
}
Parameter | Type | Description |
---|---|---|
props | RouterLinkOptions |
props object that can be passed to <router-link> . Accepts Ref s and ComputedRef s |
Returns the current route location. Equivalent to using $route
inside templates. Must be called inside of setup()
.
Signature:
export declare function useRoute(): RouteLocationNormalized
Returns the router instance. Equivalent to using $router
inside templates. Must be called inside of setup()
.
Signature:
export declare function useRouter(): Router
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.
-
Details:
Current route location. Readonly.
-
Type:
RouterOptions
-
Details:
Original options object passed to create the Router. Readonly.
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:
addRoute(parentName: string | symbol, route: RouteRecordRaw): () => void
Parameters
Parameter | Type | Description |
---|---|---|
parentName | string | symbol |
Parent Route Record where route should be appended at |
route | RouteRecordRaw |
Route Record to add |
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:
addRoute(route: RouteRecordRaw): () => void
Parameters
Parameter | Type | Description |
---|---|---|
route | RouteRecordRaw |
Route 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. :::
Add a navigation hook that is executed after every navigation. Returns a function that removes the registered hook.
Signature:
afterEach(guard: NavigationHookAfter): () => void
Parameters
Parameter | Type | Description |
---|---|---|
guard | NavigationHookAfter |
navigation hook to add |
router.afterEach((to, from, failure) => {
if (isNavigationFailure(failure)) {
console.log('failed navigation', failure)
}
})
Go back in history if possible by calling history.back()
. Equivalent to router.go(-1)
.
Signature:
back(): void
Add a navigation guard that executes before any navigation. Returns a function that removes the registered guard.
Signature:
beforeEach(guard: NavigationGuard): () => void
Parameters
Parameter | Type | Description |
---|---|---|
guard | NavigationGuard |
navigation guard to add |
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:
beforeResolve(guard: NavigationGuard): () => void
Parameters
Parameter | Type | Description |
---|---|---|
guard | NavigationGuard |
navigation guard to add |
router.beforeResolve(to => {
if (to.meta.requiresAuth && !isAuthenticated) return false
})
Go forward in history if possible by calling history.forward()
. Equivalent to router.go(1)
.
Signature:
forward(): void
Get a full list of all the route records.
Signature:
getRoutes(): RouteRecordNormalized[]
Allows you to move forward or backward through the history.
Signature:
go(delta: number): void
Parameters
Parameter | Type | Description |
---|---|---|
delta | number |
The position in the history to which you want to move, relative to the current page |
Checks if a route with a given name exists
Signature:
hasRoute(name: string | symbol): boolean
Parameters
Parameter | Type | Description |
---|---|---|
name | string | symbol |
Name of the route to check |
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:
isReady(): Promise<void>
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:
onError(handler: (error: any, to: RouteLocationNormalized, from: RouteLocationNormalized) => any): () => void
Parameters
Parameter | Type | Description |
---|---|---|
handler | (error: any, to: RouteLocationNormalized, from: RouteLocationNormalized) => any |
error handler to register |
Programmatically navigate to a new URL by pushing an entry in the history stack.
Signature:
push(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>
Parameters
Parameter | Type | Description |
---|---|---|
to | RouteLocationRaw |
Route location to navigate to |
Remove an existing route by its name.
Signature:
removeRoute(name: string | symbol): void
Parameters
Parameter | Type | Description |
---|---|---|
name | string | symbol |
Name of the route to remove |
Programmatically navigate to a new URL by replacing the current entry in the history stack.
Signature:
replace(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>
Parameters
Parameter | Type | Description |
---|---|---|
to | RouteLocationRaw |
Route location to navigate to |
Returns the normalized version of a route location. Also includes an href
property that includes any existing base
.
Signature:
resolve(to: RouteLocationRaw): RouteLocation & {
href: string
}
Parameters
Parameter | Type | Description |
---|---|---|
to | RouteLocationRaw |
Raw route location to resolve |
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:
history: RouterHistory
createRouter({
history: createWebHistory(),
// other options...
})
Default class applied to active RouterLink. If none is provided, router-link-active
will be applied.
Signature:
linkActiveClass?: string
Default class applied to exact active RouterLink. If none is provided, router-link-exact-active
will be applied.
Signature:
linkExactActiveClass?: string
Custom implementation to parse a query. Must decode query keys and values. See its counterpart, stringifyQuery.
Signature:
parseQuery?: (searchQuery: string) => Record<string, (string | null)[] | string | null>
Let's say you want to use the package qs to parse queries, you can provide both parseQuery
and stringifyQuery
:
import qs from 'qs'
createRouter({
// other options...
parseQuery: qs.parse,
stringifyQuery: qs.stringify,
})
Initial list of routes that should be added to the router.
Signature:
routes: RouteRecordRaw[]
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:
scrollBehavior?: RouterScrollBehavior
function scrollBehavior(to, from, savedPosition) {
// `to` and `from` are both route locations
// `savedPosition` can be null if there isn't one
}
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:
stringifyQuery?: (
query: Record<
string | number,
string | number | null | undefined | (string | number | null | undefined)[]
>
) => string
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
orcomponents
option because a redirect record is never reached.
-
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
-
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.
-
Type: Array of
RouteRecordRaw
(Optional) -
Details:
Nested routes of the current record.
-
See Also: Nested Routes
-
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
. Allalias
andpath
values must share the same params.
-
Type:
string | symbol
(Optional) -
Details:
Unique name for the route record.
-
Type:
NavigationGuard | NavigationGuard[]
(Optional) -
Details:
Before enter guard specific to this record. Note
beforeEnter
has no effect if the record has aredirect
property.
-
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 ascomponents
or aboolean
to be applied to each component. target location. -
See Also: Passing props to Route Components
-
Type:
boolean
(Optional) -
Details:
Makes the route matching case sensitive, defaults to
false
. Note this can also be set at a route level.
-
Type:
boolean
(Optional) -
Details:
Strictly checks the presence or absence of a trailing slash (
/
) at the end of the path. Defaults tofalse
meaning that by default a route/users
matches both/users
and/users/
. Note this can also be set at a route level.
-
Type:
RouteMeta
(Optional) -
Details:
Custom data attached to the record.
-
See Also: Meta fields
:::tip
If you want to use a functional component, make sure to add a displayName
to it.
For example:
const HomeView = () => h('div', 'HomePage')
// in TypeScript, you will need to use the FunctionalComponent type
HomeView.displayName = 'HomeView'
const routes = [{ path: '/', component: HomeView }]
:::
Normalized version of a Route Record
-
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.
-
Type:
NavigationGuard
-
Details:
Navigation guard applied when entering this record from somewhere else.
-
See Also: Navigation guards
-
Type: Array of normalized route records
-
Details:
Children route records of a route at the time it was added. Empty array if none. Note this array doesn't update when
addRoute()
andremoveRoute()
are called.
-
Type:
Record<string, Component>
-
Details:
Dictionary of named views, if none, contains an object with the key
default
.
-
Type:
RouteMeta
-
Details:
Arbitrary data attached to the record.
-
See also: Meta fields
-
Type:
string | symbol | undefined
-
Details:
Name for the route record.
undefined
if none was provided.
-
Type:
string
-
Details:
Normalized path of the record. Includes any parent's
path
.
-
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 nameddefault
.
-
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.
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:
// these three forms are equivalent
router.push('/users/posva#bio')
router.push({ path: '/users/posva', hash: '#bio' })
router.push({ name: 'users', params: { username: 'posva' }, hash: '#bio' })
// only change the hash
router.push({ hash: '#bio' })
// only change query
router.push({ query: { page: '2' } })
// change one param
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()
:
router.push({ hash: '#bio', replace: true })
// equivalent to
router.replace({ hash: '#bio' })
Resolved RouteLocationRaw that can contain redirect records. Apart from that it has the same properties as RouteLocationNormalized.
Normalized route location. Does not have any redirect records. In navigation guards, to
and from
are always of this type.
-
Type:
string
-
Details:
Encoded URL associated to the route location. Contains
path
,query
andhash
.
-
Type:
string
-
Details:
Decoded
hash
section of the URL. Always starts with a#
. Empty string if there is nohash
in the URL.
-
Type:
Record<string, string | string[]>
-
Details:
Dictionary of decoded query params extracted from the
search
section of the URL.
-
Type:
RouteRecordNormalized[]
-
Details:
Array of normalized route records that were matched with the given route location.
-
Type:
RouteMeta
-
Details:
Arbitrary data attached to all matched records merged (non recursively) from parent to child.
-
See also: Meta fields
-
Type:
string | symbol | undefined | null
-
Details:
Name for the route record.
undefined
if none was provided.
-
Type:
Record<string, string | string[]>
-
Details:
Dictionary of decoded params extracted from
path
.
-
Type:
string
-
Details:
Encoded
pathname
section of the URL associated to the route location.
-
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 callednext()
with a route location.undefined
if there was no redirection.
-
Type:
RouteLocationNormalized
-
Details:
Route location we were navigating from
-
Type:
RouteLocationNormalized
-
Details:
Route location we were navigating to
-
Type:
NavigationFailureType
-
Details:
Type of the navigation failure.
-
See Also: Navigation Failures
-
Arguments:
RouteLocationNormalized
to - Route location we are navigating toRouteLocationNormalized
from - Route location we are navigating fromFunction
next (Optional) - Callback to validate the navigation
-
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 fornext
) are:undefined | void | true
: validates the navigationfalse
: cancels the navigationRouteLocationRaw
: redirects to a different location(vm: ComponentPublicInstance) => any
only forbeforeRouteEnter
: A callback to be executed once the navigation completes. Receives the route component instance as the parameter.
-
See Also: Navigation Guards
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.
- beforeRouteEnter
- beforeRouteUpdate
- beforeRouteLeave
See In Component Guards.