vue-router
- Version 4.5.0
- Published
- 861 kB
- 1 dependency
- MIT license
Install
npm i vue-router
yarn add vue-router
pnpm add vue-router
Overview
Overview not available.
Index
Variables
Functions
Interfaces
Enums
Type Aliases
- LocationQuery
- LocationQueryRaw
- NavigationGuardNextCallback
- NavigationGuardReturn
- ParamValue
- ParamValueOneOrMore
- ParamValueZeroOrMore
- ParamValueZeroOrOne
- PathParserOptions
- RouteComponent
- RouteLocation
- RouteLocationAsPath
- RouteLocationAsRelative
- RouteLocationAsString
- RouteLocationAsStringTyped
- RouteLocationNormalized
- RouteLocationNormalizedLoaded
- RouteLocationRaw
- RouteLocationResolved
- RouteMap
- RouteMapGeneric
- RouteParams
- RouteParamsGeneric
- RouteParamsRaw
- RouteParamsRawGeneric
- RouteRecord
- RouteRecordName
- RouteRecordNameGeneric
- RouteRecordRaw
Variables
variable RouterLink
const RouterLink: _RouterLinkI;
Component to render a link that triggers a navigation on click.
variable RouterView
const RouterView: new () => { $props: AllowedComponentProps & ComponentCustomProps & VNodeProps & RouterViewProps; $slots: { default?: ({ Component, route, }: { Component: VNode; route: RouteLocationNormalizedLoaded; }) => VNode[]; };};
Component to display the current route the user is at.
variable START_LOCATION
const START_LOCATION: RouteLocationNormalizedLoadedGeneric;
Initial route location where the router is. Can be used in navigation guards to differentiate the initial navigation.
Example 1
import { START_LOCATION } from 'vue-router'router.beforeEach((to, from) => {if (from === START_LOCATION) {// initial navigation}})
Functions
function createMemoryHistory
createMemoryHistory: (base?: string) => RouterHistory;
Creates an in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. It's up to the user to replace that location with the starter location by either calling
router.push
orrouter.replace
.Parameter base
Base applied to all urls, defaults to '/'
Returns
a history object that can be passed to the router constructor
function createRouter
createRouter: (options: RouterOptions) => Router;
Creates a Router instance that can be used by a Vue app.
Parameter options
function createWebHashHistory
createWebHashHistory: (base?: string) => RouterHistory;
Creates a hash history. Useful for web applications with no host (e.g.
file://
) or when configuring a server to handle any URL is not possible.Parameter base
optional base to provide. Defaults to
location.pathname + location.search
If there is a<base>
tag in thehead
, 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, it'shref
value **has to match this parameter** (ignoring anything after the#
).Example 1
// at https://example.com/foldercreateWebHashHistory() // 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 urlscreateWebHashHistory('/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 ignoredcreateWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
function createWebHistory
createWebHistory: (base?: string) => RouterHistory;
Creates an HTML5 history. Most common history for single page applications.
Parameter base
function isNavigationFailure
isNavigationFailure: { ( error: any, type?: ErrorTypes.NAVIGATION_GUARD_REDIRECT ): error is NavigationRedirectError; ( error: any, type?: ErrorTypes | NavigationFailureType ): error is NavigationFailure;};
Check if an object is a NavigationFailure.
Parameter error
possible NavigationFailure
Parameter type
optional types to check for
Example 1
import { isNavigationFailure, NavigationFailureType } from 'vue-router'router.afterEach((to, from, failure) => {// Any kind of navigation failureif (isNavigationFailure(failure)) {// ...}// Only duplicated navigationsif (isNavigationFailure(failure, NavigationFailureType.duplicated)) {// ...}// Aborted or canceled navigationsif (isNavigationFailure(failure, NavigationFailureType.aborted | NavigationFailureType.canceled)) {// ...}})
function loadRouteLocation
loadRouteLocation: ( route: RouteLocation | RouteLocationNormalized) => Promise<RouteLocationNormalizedLoaded>;
Ensures a route is loaded, so it can be passed as o prop to
<RouterView>
.Parameter route
resolved route to load
function onBeforeRouteLeave
onBeforeRouteLeave: (leaveGuard: NavigationGuard) => void;
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.
Parameter leaveGuard
function onBeforeRouteUpdate
onBeforeRouteUpdate: (updateGuard: NavigationGuard) => void;
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.
Parameter updateGuard
function useLink
useLink: <Name extends string | symbol = string | symbol>( props: UseLinkOptions<Name>) => UseLinkReturn<Name>;
Returns the internal behavior of a RouterLink without the rendering part.
Parameter props
a
to
location and an optionalreplace
flag
function useRoute
useRoute: <Name extends string | symbol = string | symbol>( _name?: Name) => RouteLocationNormalizedLoaded<Name>;
Returns the current route location. Equivalent to using
$route
inside templates.
function useRouter
useRouter: () => Router;
Returns the router instance. Equivalent to using
$router
inside templates.
Interfaces
interface HistoryState
interface HistoryState {}
Allowed HTML history.state
index signature
[x: number]: HistoryStateValue;
index signature
[x: string]: HistoryStateValue;
interface MatcherLocation
interface MatcherLocation {}
Normalized/resolved Route location that returned by the matcher.
property matched
matched: RouteRecord[];
Array of RouteRecord containing components as they were passed when adding records. It can also contain redirect records. This can't be used directly
property meta
meta: RouteMeta;
Merged
meta
properties from all the matched route records.
property name
name: RouteRecordNameGeneric | null | undefined;
Name of the matched record
property params
params: RouteParamsGeneric;
Object of decoded params extracted from the
path
.
property path
path: string;
Percentage encoded pathname section of the URL.
interface NavigationFailure
interface NavigationFailure extends Error {}
Extended Error that contains extra information regarding a failed navigation.
property from
from: RouteLocationNormalized;
Route location we were navigating from
property to
to: RouteLocationNormalized;
Route location we were navigating to
property type
type: | ErrorTypes.NAVIGATION_CANCELLED | ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED;
Type of the navigation. One of NavigationFailureType
interface NavigationGuard
interface NavigationGuard {}
Navigation Guard.
call signature
( to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, next: NavigationGuardNext): _Awaitable<NavigationGuardReturn>;
interface NavigationGuardNext
interface NavigationGuardNext {}
next()
callback passed to navigation guards.
call signature
(): void;
call signature
(error: Error): void;
call signature
(location: RouteLocationRaw): void;
call signature
(valid: boolean | undefined): void;
call signature
(cb: NavigationGuardNextCallback): void;
interface NavigationGuardWithThis
interface NavigationGuardWithThis<T> {}
Navigation Guard with a type parameter for
this
.See Also
call signature
( this: T, to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, next: NavigationGuardNext): _Awaitable<NavigationGuardReturn>;
interface NavigationHookAfter
interface NavigationHookAfter {}
Navigation hook triggered after a navigation is settled.
call signature
( to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, failure?: NavigationFailure | void): unknown;
interface RouteLocationAsPathGeneric
interface RouteLocationAsPathGeneric extends RouteQueryAndHash, RouteLocationOptions {}
Generic version of RouteLocationAsPath. It is used when no RouteMap is provided.
property path
path: string;
Percentage encoded pathname section of the URL.
interface RouteLocationAsPathTyped
interface RouteLocationAsPathTyped< RouteMap extends RouteMapGeneric = RouteMapGeneric, Name extends keyof RouteMap = keyof RouteMap> extends RouteLocationAsPathGeneric {}
Helper to generate a type safe version of the RouteLocationAsPath type.
property path
path: _LiteralUnion<RouteMap[Name]['path']>;
interface RouteLocationAsRelativeGeneric
interface RouteLocationAsRelativeGeneric extends RouteQueryAndHash, RouteLocationOptions {}
Generic version of RouteLocationAsRelative. It is used when no RouteMap is provided.
interface RouteLocationAsRelativeTyped
interface RouteLocationAsRelativeTyped< RouteMap extends RouteMapGeneric = RouteMapGeneric, Name extends keyof RouteMap = keyof RouteMap> extends RouteLocationAsRelativeGeneric {}
Helper to generate a type safe version of the RouteLocationAsRelative type.
interface RouteLocationGeneric
interface RouteLocationGeneric extends _RouteLocationBase {}
Generic version of RouteLocation. It is used when no RouteMap is provided.
property matched
matched: RouteRecord[];
Array of RouteRecord containing components as they were passed when adding records. It can also contain redirect records. This can't be used directly. **This property is non-enumerable**.
interface RouteLocationMatched
interface RouteLocationMatched extends RouteRecordNormalized {}
property components
components: Record<string, RouteComponent> | null | undefined;
interface RouteLocationNormalizedGeneric
interface RouteLocationNormalizedGeneric extends _RouteLocationBase {}
Generic version of RouteLocationNormalized that is used when no RouteMap is provided.
property matched
matched: RouteRecordNormalized[];
Array of RouteRecordNormalized
property name
name: RouteRecordNameGeneric;
property params
params: RouteParamsGeneric;
interface RouteLocationNormalizedLoadedGeneric
interface RouteLocationNormalizedLoadedGeneric extends RouteLocationNormalizedGeneric {}
Generic version of RouteLocationNormalizedLoaded that is used when no RouteMap is provided.
property matched
matched: RouteLocationMatched[];
Array of RouteLocationMatched containing only plain components (any lazy-loaded components have been loaded and were replaced inside the
components
object) so it can be directly used to display routes. It cannot contain redirect records either. **This property is non-enumerable**.
interface RouteLocationNormalizedLoadedTyped
interface RouteLocationNormalizedLoadedTyped< RouteMap extends RouteMapGeneric = RouteMapGeneric, Name extends keyof RouteMap = keyof RouteMap> extends RouteLocationNormalizedLoadedGeneric {}
Helper to generate a type safe version of the RouteLocationNormalizedLoaded type.
interface RouteLocationNormalizedTyped
interface RouteLocationNormalizedTyped< RouteMap extends RouteMapGeneric = RouteMapGeneric, Name extends keyof RouteMap = keyof RouteMap> extends RouteLocationNormalizedGeneric {}
Helper to generate a type safe version of the RouteLocationNormalized type.
property matched
matched: RouteRecordNormalized[];
Array of RouteRecordNormalized
property name
name: Extract<Name, string | symbol>;
property params
params: RouteMap[Name]['params'];
interface RouteLocationOptions
interface RouteLocationOptions {}
Common options for all navigation methods.
property force
force?: boolean;
Triggers the navigation even if the location is the same as the current one. Note this will also add a new entry to the history unless
replace: true
is passed.
property replace
replace?: boolean;
Replace the entry in the history instead of pushing a new entry
property state
state?: HistoryState;
State to save using the History API. This cannot contain any reactive values and some primitives like Symbols are forbidden. More info at https://developer.mozilla.org/en-US/docs/Web/API/History/state
interface RouteLocationResolvedGeneric
interface RouteLocationResolvedGeneric extends RouteLocationGeneric {}
Generic version of RouteLocationResolved. It is used when no RouteMap is provided.
property href
href: string;
Resolved
href
for the route location that will be set on the<a href="...">
.
interface RouteLocationResolvedTyped
interface RouteLocationResolvedTyped< RouteMap extends RouteMapGeneric, Name extends keyof RouteMap> extends RouteLocationTyped<RouteMap, Name> {}
Helper to generate a type safe version of the RouteLocationResolved type.
property href
href: string;
Resolved
href
for the route location that will be set on the<a href="...">
.
interface RouteLocationTyped
interface RouteLocationTyped< RouteMap extends RouteMapGeneric, Name extends keyof RouteMap> extends RouteLocationGeneric {}
Helper to generate a type safe version of the RouteLocation type.
interface RouteMeta
interface RouteMeta extends Record<string | number | symbol, unknown> {}
Interface to type
meta
fields in route records.Example 1
// typings.d.ts or router.tsimport 'vue-router';declare module 'vue-router' {interface RouteMeta {requiresAuth?: boolean}}
interface Router
interface Router {}
Router instance.
property currentRoute
readonly currentRoute: Ref<RouteLocationNormalizedLoaded>;
Current RouteLocationNormalized
property listening
listening: boolean;
Allows turning off the listening of history events. This is a low level api for micro-frontend.
property options
readonly options: RouterOptions;
Original options object passed to create the Router
method addRoute
addRoute: { ( parentName: NonNullable<RouteRecordNameGeneric>, route: RouteRecordRaw ): () => void; (route: RouteRecordRaw): () => void;};
Add a new route record as the child of an existing route.
Parameter parentName
Parent Route Record where
route
should be appended atParameter route
Route Record to add
Add a new route record to the router.
Parameter route
Route Record to add
method afterEach
afterEach: (guard: NavigationHookAfter) => () => void;
Add a navigation hook that is executed after every navigation. Returns a function that removes the registered hook.
Parameter guard
navigation hook to add
Returns
a function that removes the registered hook
Example 1
router.afterEach((to, from, failure) => {if (isNavigationFailure(failure)) {console.log('failed navigation', failure)}})
method back
back: () => ReturnType<Router['go']>;
Go back in history if possible by calling
history.back()
. Equivalent torouter.go(-1)
.
method beforeEach
beforeEach: (guard: NavigationGuardWithThis<undefined>) => () => void;
Add a navigation guard that executes before any navigation. Returns a function that removes the registered guard.
Parameter guard
navigation guard to add
method beforeResolve
beforeResolve: (guard: NavigationGuardWithThis<undefined>) => () => void;
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.
Parameter guard
navigation guard to add
Returns
a function that removes the registered guard
Example 1
router.beforeResolve(to => {if (to.meta.requiresAuth && !isAuthenticated) return false})
method clearRoutes
clearRoutes: () => void;
Delete all routes from the router matcher.
method forward
forward: () => ReturnType<Router['go']>;
Go forward in history if possible by calling
history.forward()
. Equivalent torouter.go(1)
.
method getRoutes
getRoutes: () => RouteRecord[];
Get a full list of all the route records.
method go
go: (delta: number) => void;
Allows you to move forward or backward through the history. Calls
history.go()
.Parameter delta
The position in the history to which you want to move, relative to the current page
method hasRoute
hasRoute: (name: NonNullable<RouteRecordNameGeneric>) => boolean;
Checks if a route with a given name exists
Parameter name
Name of the route to check
method isReady
isReady: () => Promise<void>;
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.
method onError
onError: (handler: _ErrorListener) => () => 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.Parameter handler
error handler to register
method push
push: (to: RouteLocationRaw) => Promise<NavigationFailure | void | undefined>;
Programmatically navigate to a new URL by pushing an entry in the history stack.
Parameter to
Route location to navigate to
method removeRoute
removeRoute: (name: NonNullable<RouteRecordNameGeneric>) => void;
Remove an existing route by its name.
Parameter name
Name of the route to remove
method replace
replace: (to: RouteLocationRaw) => Promise<NavigationFailure | void | undefined>;
Programmatically navigate to a new URL by replacing the current entry in the history stack.
Parameter to
Route location to navigate to
method resolve
resolve: { <Name extends string | symbol = string | symbol>( to: RouteLocationAsRelativeTyped<RouteMap, Name>, currentLocation?: RouteLocationNormalizedLoaded ): RouteLocationResolved<Name>; ( to: string | RouteLocationAsRelativeGeneric | RouteLocationAsPathGeneric, currentLocation?: RouteLocationNormalizedLoadedGeneric ): RouteLocationResolvedGeneric;};
Returns the normalized version of a route location. Also includes an
href
property that includes any existingbase
. By default, thecurrentLocation
used isrouter.currentRoute
and should only be overridden in advanced use cases.Parameter to
Raw route location to resolve
Parameter currentLocation
Optional current location to resolve against
interface RouteRecordInfo
interface RouteRecordInfo< Name extends string | symbol = string, Path extends string = string, ParamsRaw extends RouteParamsRawGeneric = RouteParamsRawGeneric, Params extends RouteParamsGeneric = RouteParamsGeneric, Meta extends RouteMeta = RouteMeta> {}
Helper type to define a Typed
RouteRecord
See Also
interface RouteRecordMultipleViews
interface RouteRecordMultipleViews extends _RouteRecordBase {}
Route Record defining multiple named components with the
components
option.
property children
children?: never;
property component
component?: never;
property components
components: Record<string, RawRouteComponent>;
Components to display when the URL matches this route. Allow using named views.
property props
props?: Record<string, _RouteRecordProps> | boolean;
Allow passing down params as props to the component rendered by
router-view
. Should be an object with the same keys ascomponents
or a boolean to be applied to every component.
property redirect
redirect?: never;
interface RouteRecordMultipleViewsWithChildren
interface RouteRecordMultipleViewsWithChildren extends _RouteRecordBase {}
Route Record defining multiple named components with the
components
option and children.
property children
children: RouteRecordRaw[];
property component
component?: never;
property components
components?: Record<string, RawRouteComponent> | null | undefined;
Components to display when the URL matches this route. Allow using named views.
property props
props?: Record<string, _RouteRecordProps> | boolean;
Allow passing down params as props to the component rendered by
router-view
. Should be an object with the same keys ascomponents
or a boolean to be applied to every component.
interface RouteRecordNormalized
interface RouteRecordNormalized {}
Normalized version of a route record.
property aliasOf
aliasOf: RouteRecordNormalized | undefined;
Defines if this record is the alias of another one. This property is
undefined
if the record is the original one.
property beforeEnter
beforeEnter: _RouteRecordBase['beforeEnter'];
Registered beforeEnter guards
property children
children: RouteRecordRaw[];
Nested route records.
property components
components: RouteRecordMultipleViews['components'] | null | undefined;
See documentation for RouteRecordMultipleViews.components.
property instances
instances: Record<string, ComponentPublicInstance | undefined | null>;
Mounted route component instances Having the instances on the record mean beforeRouteUpdate and beforeRouteLeave guards can only be invoked with the latest mounted app instance if there are multiple application instances rendering the same view, basically duplicating the content on the page, which shouldn't happen in practice. It will work if multiple apps are rendering different named views.
property meta
meta: Exclude<_RouteRecordBase['meta'], void>;
See documentation for _RouteRecordBase.meta.
property name
name: _RouteRecordBase['name'];
See documentation for _RouteRecordBase.name.
property path
path: _RouteRecordBase['path'];
See documentation for _RouteRecordBase.path.
property props
props: Record<string, _RouteRecordProps>;
See documentation for RouteRecordMultipleViews.props.
property redirect
redirect: _RouteRecordBase['redirect'] | undefined;
See documentation for _RouteRecordBase.redirect.
interface RouteRecordRedirect
interface RouteRecordRedirect extends _RouteRecordBase {}
Route Record that defines a redirect. Cannot have
component
orcomponents
as it is never rendered.
property component
component?: never;
property components
components?: never;
property props
props?: never;
property redirect
redirect: RouteRecordRedirectOption;
interface RouteRecordSingleView
interface RouteRecordSingleView extends _RouteRecordBase {}
Route Record defining one single component with the
component
option.
property children
children?: never;
property component
component: RawRouteComponent;
Component to display when the URL matches this route.
property components
components?: never;
property props
props?: _RouteRecordProps;
Allow passing down params as props to the component rendered by
router-view
.
property redirect
redirect?: never;
interface RouteRecordSingleViewWithChildren
interface RouteRecordSingleViewWithChildren extends _RouteRecordBase {}
Route Record defining one single component with a nested view.
property children
children: RouteRecordRaw[];
property component
component?: RawRouteComponent | null | undefined;
Component to display when the URL matches this route.
property components
components?: never;
property props
props?: _RouteRecordProps;
Allow passing down params as props to the component rendered by
router-view
.
interface RouterHistory
interface RouterHistory {}
Interface implemented by History implementations that can be passed to the router as Router.history
Modifiers
@alpha
property base
readonly base: string;
Base path that is prepended to every url. This allows hosting an SPA at a sub-folder of a domain like
example.com/sub-folder
by having abase
of/sub-folder
property location
readonly location: HistoryLocation;
Current History location
property state
readonly state: HistoryState;
Current History state
method createHref
createHref: (location: HistoryLocation) => string;
Generates the corresponding href to be used in an anchor tag.
Parameter location
history location that should create an href
method destroy
destroy: () => void;
Clears any event listener attached by the history implementation.
method go
go: (delta: number, triggerListeners?: boolean) => void;
Traverses history in a given direction.
Parameter delta
distance to travel. If delta is < 0, it will go back, if it's > 0, it will go forward by that amount of entries.
Parameter triggerListeners
whether this should trigger listeners attached to the history
Example 1
myHistory.go(-1) // equivalent to window.history.back()myHistory.go(1) // equivalent to window.history.forward()
method listen
listen: (callback: NavigationCallback) => () => void;
Attach a listener to the History implementation that is triggered when the navigation is triggered from outside (like the Browser back and forward buttons) or when passing
true
to RouterHistory.back and RouterHistory.forwardParameter callback
listener to attach
Returns
a callback to remove the listener
method push
push: (to: HistoryLocation, data?: HistoryState) => void;
Navigates to a location. In the case of an HTML5 History implementation, this will call
history.pushState
to effectively change the URL.Parameter to
location to push
Parameter data
optional HistoryState to be associated with the navigation entry
method replace
replace: (to: HistoryLocation, data?: HistoryState) => void;
Same as RouterHistory.push but performs a
history.replaceState
instead ofhistory.pushState
Parameter to
location to set
Parameter data
optional HistoryState to be associated with the navigation entry
interface RouterLinkProps
interface RouterLinkProps extends RouterLinkOptions {}
property activeClass
activeClass?: string;
Class to apply when the link is active
property ariaCurrentValue
ariaCurrentValue?: | 'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false';
Value passed to the attribute
aria-current
when the link is exact active.
property custom
custom?: boolean;
Whether RouterLink should not wrap its content in an
a
tag. Useful when usingv-slot
to create a custom RouterLink
property exactActiveClass
exactActiveClass?: string;
Class to apply when the link is exact active
property viewTransition
viewTransition?: boolean;
Pass the returned promise of
router.push()
todocument.startViewTransition()
if supported.
interface RouterOptions
interface RouterOptions extends PathParserOptions {}
Options to initialize a Router instance.
property history
history: RouterHistory;
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 withcreateWebHashHistory
that does not require any configuration on the server but isn't handled at all by search engines and does poorly on SEO.Example 1
createRouter({history: createWebHistory(),// other options...})
property linkActiveClass
linkActiveClass?: string;
Default class applied to active RouterLink. If none is provided,
router-link-active
will be applied.
property linkExactActiveClass
linkExactActiveClass?: string;
Default class applied to exact active RouterLink. If none is provided,
router-link-exact-active
will be applied.
property parseQuery
parseQuery?: typeof parseQuery;
Custom implementation to parse a query. See its counterpart, RouterOptions.stringifyQuery.
Example 1
Let's say you want to use the [qs package](https://github.com/ljharb/qs) to parse queries, you can provide both
parseQuery
andstringifyQuery
:import qs from 'qs'createRouter({// other options...parseQuery: qs.parse,stringifyQuery: qs.stringify,})
property routes
routes: Readonly<RouteRecordRaw[]>;
Initial list of routes that should be added to the router.
property scrollBehavior
scrollBehavior?: RouterScrollBehavior;
Function to control scrolling when navigating between pages. Can return a Promise to delay scrolling. Check ScrollBehavior.
Example 1
function scrollBehavior(to, from, savedPosition) {// `to` and `from` are both route locations// `savedPosition` can be null if there isn't one}
property stringifyQuery
stringifyQuery?: typeof stringifyQuery;
Custom implementation to stringify a query object. Should not prepend a leading
?
. parseQuery counterpart to handle query parsing.
interface RouterScrollBehavior
interface RouterScrollBehavior {}
Type of the
scrollBehavior
option that can be passed tocreateRouter
.
call signature
( to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, savedPosition: _ScrollPositionNormalized | null): Awaitable<ScrollPosition | false | void>;
Parameter to
Route location where we are navigating to
Parameter from
Route location where we are navigating from
Parameter savedPosition
saved position if it exists,
null
otherwise
interface RouterViewProps
interface RouterViewProps {}
interface UseLinkOptions
interface UseLinkOptions<Name extends keyof RouteMap = keyof RouteMap> {}
Options passed to useLink.
property replace
replace?: MaybeRef<boolean | undefined>;
property to
to: MaybeRef< | RouteLocationAsString | RouteLocationAsRelativeTyped<RouteMap, Name> | RouteLocationAsPath | RouteLocationRaw>;
property viewTransition
viewTransition?: boolean;
Pass the returned promise of
router.push()
todocument.startViewTransition()
if supported.
Enums
enum NavigationFailureType
enum NavigationFailureType { aborted = 4, cancelled = 8, duplicated = 16,}
Enumeration with all possible types for navigation failures. Can be passed to isNavigationFailure to check for specific failures.
member aborted
aborted = 4
An aborted navigation is a navigation that failed because a navigation guard returned
false
or callednext(false)
member cancelled
cancelled = 8
A cancelled navigation is a navigation that failed because a more recent navigation finished started (not necessarily finished).
member duplicated
duplicated = 16
A duplicated navigation is a navigation that failed because it was initiated while already being at the exact same location.
Type Aliases
type LocationQuery
type LocationQuery = Record<string, LocationQueryValue | LocationQueryValue[]>;
Normalized query object that appears in RouteLocationNormalized
Modifiers
@public
type LocationQueryRaw
type LocationQueryRaw = Record< string | number, LocationQueryValueRaw | LocationQueryValueRaw[]>;
Loose LocationQuery object that can be passed to functions like Router.push and Router.replace or anywhere when creating a RouteLocationRaw
Modifiers
@public
type NavigationGuardNextCallback
type NavigationGuardNextCallback = (vm: ComponentPublicInstance) => unknown;
Callback that can be passed to
next()
inbeforeRouteEnter()
guards.
type NavigationGuardReturn
type NavigationGuardReturn = void | Error | boolean | RouteLocationRaw;
Return types for a Navigation Guard. Based on
TypesConfig
See Also
type ParamValue
type ParamValue<isRaw extends boolean> = true extends isRaw ? string | number : string;
Utility type for raw and non raw params like :id
type ParamValueOneOrMore
type ParamValueOneOrMore<isRaw extends boolean> = [ ParamValue<isRaw>, ...ParamValue<isRaw>[]];
Utility type for raw and non raw params like :id+
type ParamValueZeroOrMore
type ParamValueZeroOrMore<isRaw extends boolean> = true extends isRaw ? ParamValue<isRaw>[] | undefined | null : ParamValue<isRaw>[] | undefined;
Utility type for raw and non raw params like :id*
type ParamValueZeroOrOne
type ParamValueZeroOrOne<isRaw extends boolean> = true extends isRaw ? string | number | null | undefined : string;
Utility type for raw and non raw params like :id?
type PathParserOptions
type PathParserOptions = Pick<_PathParserOptions, 'end' | 'sensitive' | 'strict'>;
type RouteComponent
type RouteComponent = Component | DefineComponent;
Allowed Component in RouteLocationMatched
type RouteLocation
type RouteLocation<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationGeneric : RouteLocationTypedList<RouteMap>[Name];
RouteLocationRaw resolved using the matcher
type RouteLocationAsPath
type RouteLocationAsPath<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationAsPathGeneric : RouteLocationAsPathTypedList<RouteMap>[Name];
Route location as an object with a
path
property.
type RouteLocationAsRelative
type RouteLocationAsRelative<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationAsRelativeGeneric : RouteLocationAsRelativeTypedList<RouteMap>[Name];
Route location relative to the current location. It accepts other properties than
path
likeparams
,query
andhash
to conveniently change them.
type RouteLocationAsString
type RouteLocationAsString<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? string : _LiteralUnion<RouteLocationAsStringTypedList<RouteMap>[Name], string>;
Same as RouteLocationAsPath but as a string literal.
type RouteLocationAsStringTyped
type RouteLocationAsStringTyped< RouteMap extends RouteMapGeneric = RouteMapGeneric, Name extends keyof RouteMap = keyof RouteMap> = RouteMap[Name]['path'];
Helper to generate a type safe version of the RouteLocationAsString type.
type RouteLocationNormalized
type RouteLocationNormalized<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationNormalizedGeneric : RouteLocationNormalizedTypedList<RouteMap>[Name];
Similar to RouteLocation but its `matched` property cannot contain redirect records
type RouteLocationNormalizedLoaded
type RouteLocationNormalizedLoaded<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationNormalizedLoadedGeneric : RouteLocationNormalizedLoadedTypedList<RouteMap>[Name];
Similar to RouteLocationNormalized but its
components
do not contain any function to lazy load components. In other words, it's ready to be rendered by<RouterView>
.
type RouteLocationRaw
type RouteLocationRaw<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? | RouteLocationAsString | RouteLocationAsRelativeGeneric | RouteLocationAsPathGeneric : | _LiteralUnion<RouteLocationAsStringTypedList<RouteMap>[Name], string> | RouteLocationAsRelativeTypedList<RouteMap>[Name] | RouteLocationAsPathTypedList<RouteMap>[Name];
Route location that can be passed to
router.push()
and other user-facing APIs.
type RouteLocationResolved
type RouteLocationResolved<Name extends keyof RouteMap = keyof RouteMap> = RouteMapGeneric extends RouteMap ? RouteLocationResolvedGeneric : RouteLocationResolvedTypedList<RouteMap>[Name];
Route location resolved with `router.resolve()`.
type RouteMap
type RouteMap = TypesConfig extends Record<'RouteNamedMap', infer RouteNamedMap> ? RouteNamedMap : RouteMapGeneric;
Convenience type to get the typed RouteMap or a generic one if not provided. It is extracted from the TypesConfig if it exists, it becomes RouteMapGeneric otherwise.
type RouteMapGeneric
type RouteMapGeneric = Record<string | symbol, RouteRecordInfo>;
Generic version of the
RouteMap
.
type RouteParams
type RouteParams<Name extends keyof RouteMap = keyof RouteMap> = RouteMap[Name]['params'];
Generate a type safe params for a route location. Requires the name of the route to be passed as a generic.
See Also
type RouteParamsGeneric
type RouteParamsGeneric = Record<string, RouteParamValue | RouteParamValue[]>;
type RouteParamsRaw
type RouteParamsRaw<Name extends keyof RouteMap = keyof RouteMap> = RouteMap[Name]['paramsRaw'];
Generate a type safe raw params for a route location. Requires the name of the route to be passed as a generic.
See Also
type RouteParamsRawGeneric
type RouteParamsRawGeneric = Record< string, RouteParamValueRaw | Exclude<RouteParamValueRaw, null | undefined>[]>;
type RouteRecord
type RouteRecord = RouteRecordNormalized;
See documentation for RouteRecordNormalized.
type RouteRecordName
type RouteRecordName = RouteMapGeneric extends RouteMap ? RouteRecordNameGeneric : keyof RouteMap;
Possible values for a route record **after normalization**
NOTE: since
RouteRecordName
is a type, it evaluates too early and it's often the generic version RouteRecordNameGeneric. If you need a typed version of all of the names of routes, use `keyof RouteMap`
type RouteRecordNameGeneric
type RouteRecordNameGeneric = string | symbol | undefined;
Generic version of RouteRecordName.
type RouteRecordRaw
type RouteRecordRaw = | RouteRecordSingleView | RouteRecordSingleViewWithChildren | RouteRecordMultipleViews | RouteRecordMultipleViewsWithChildren | RouteRecordRedirect;
Package Files (1)
Dependencies (1)
Dev Dependencies (28)
- @microsoft/api-extractor
- @rollup/plugin-alias
- @rollup/plugin-commonjs
- @rollup/plugin-node-resolve
- @rollup/plugin-replace
- @rollup/plugin-terser
- @types/jsdom
- @types/nightwatch
- @vitejs/plugin-vue
- @vue/compiler-sfc
- @vue/server-renderer
- @vue/test-utils
- browserstack-local
- chromedriver
- connect-history-api-fallback
- conventional-changelog-cli
- dotenv
- faked-promise
- geckodriver
- happy-dom
- nightwatch
- nightwatch-helpers
- rimraf
- rollup
- rollup-plugin-analyzer
- rollup-plugin-typescript2
- vite
- vue
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/vue-router
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/vue-router)
- HTML<a href="https://www.jsdocs.io/package/vue-router"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 6267 ms. - Missing or incorrect documentation? Open an issue for this package.