vue-router.d.ts 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. import { AllowedComponentProps } from 'vue';
  2. import { App } from 'vue';
  3. import { Component } from 'vue';
  4. import { ComponentCustomProps } from 'vue';
  5. import { ComponentPublicInstance } from 'vue';
  6. import { ComputedRef } from 'vue';
  7. import { InjectionKey } from 'vue';
  8. import { Ref } from 'vue';
  9. import { UnwrapRef } from 'vue';
  10. import { VNode } from 'vue';
  11. import { VNodeProps } from 'vue';
  12. declare type Awaitable<T> = T | Promise<T>;
  13. /**
  14. * 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.
  15. * It's up to the user to replace that location with the starter location by either calling `router.push` or `router.replace`.
  16. *
  17. * @param base - Base applied to all urls, defaults to '/'
  18. * @returns a history object that can be passed to the router constructor
  19. */
  20. export declare function createMemoryHistory(base?: string): RouterHistory;
  21. /**
  22. * Creates a Router instance that can be used by a Vue app.
  23. *
  24. * @param options - {@link RouterOptions}
  25. */
  26. export declare function createRouter(options: RouterOptions): Router;
  27. /**
  28. * Creates a Router Matcher.
  29. *
  30. * @internal
  31. * @param routes - array of initial routes
  32. * @param globalOptions - global route options
  33. */
  34. export declare function createRouterMatcher(routes: RouteRecordRaw[], globalOptions: PathParserOptions): RouterMatcher;
  35. /**
  36. * Creates a hash history. Useful for web applications with no host (e.g.
  37. * `file://`) or when configuring a server to handle any URL is not possible.
  38. *
  39. * @param base - optional base to provide. Defaults to `location.pathname +
  40. * location.search` If there is a `<base>` tag in the `head`, its value will be
  41. * ignored in favor of this parameter **but note it affects all the
  42. * history.pushState() calls**, meaning that if you use a `<base>` tag, it's
  43. * `href` value **has to match this parameter** (ignoring anything after the
  44. * `#`).
  45. *
  46. * @example
  47. * ```js
  48. * // at https://example.com/folder
  49. * createWebHashHistory() // gives a url of `https://example.com/folder#`
  50. * createWebHashHistory('/folder/') // gives a url of `https://example.com/folder/#`
  51. * // if the `#` is provided in the base, it won't be added by `createWebHashHistory`
  52. * createWebHashHistory('/folder/#/app/') // gives a url of `https://example.com/folder/#/app/`
  53. * // you should avoid doing this because it changes the original url and breaks copying urls
  54. * createWebHashHistory('/other-folder/') // gives a url of `https://example.com/other-folder/#`
  55. *
  56. * // at file:///usr/etc/folder/index.html
  57. * // for locations with no `host`, the base is ignored
  58. * createWebHashHistory('/iAmIgnored') // gives a url of `file:///usr/etc/folder/index.html#`
  59. * ```
  60. */
  61. export declare function createWebHashHistory(base?: string): RouterHistory;
  62. /**
  63. * Creates an HTML5 history. Most common history for single page applications.
  64. *
  65. * @param base -
  66. */
  67. export declare function createWebHistory(base?: string): RouterHistory;
  68. /**
  69. * Internal type to define an ErrorHandler
  70. *
  71. * @param error - error thrown
  72. * @param to - location we were navigating to when the error happened
  73. * @param from - location we were navigating from when the error happened
  74. * @internal
  75. */
  76. declare type _ErrorHandler = (error: any, to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded) => any;
  77. /**
  78. * Flags so we can combine them when checking for multiple errors
  79. */
  80. declare const enum ErrorTypes {
  81. MATCHER_NOT_FOUND = 1,
  82. NAVIGATION_GUARD_REDIRECT = 2,
  83. NAVIGATION_ABORTED = 4,
  84. NAVIGATION_CANCELLED = 8,
  85. NAVIGATION_DUPLICATED = 16
  86. }
  87. declare type HistoryLocation = string;
  88. /**
  89. * Allowed HTML history.state
  90. */
  91. export declare interface HistoryState {
  92. [x: number]: HistoryStateValue;
  93. [x: string]: HistoryStateValue;
  94. }
  95. declare interface HistoryStateArray extends Array<HistoryStateValue> {
  96. }
  97. /**
  98. * Allowed variables in HTML5 history state
  99. */
  100. declare type HistoryStateValue = string | number | boolean | null | undefined | HistoryState | HistoryStateArray;
  101. /**
  102. * Check if an object is a {@link NavigationFailure}.
  103. *
  104. * @example
  105. * ```js
  106. * import { isNavigationFailure, NavigationFailureType } from 'vue-router'
  107. *
  108. * router.afterEach((to, from, failure) => {
  109. * // Any kind of navigation failure
  110. * if (isNavigationFailure(failure)) {
  111. * // ...
  112. * }
  113. * // Only duplicated navigations
  114. * if (isNavigationFailure(failure, NavigationFailureType.duplicated)) {
  115. * // ...
  116. * }
  117. * // Aborted or canceled navigations
  118. * if (isNavigationFailure(failure, NavigationFailureType.aborted | NavigationFailureType.canceled)) {
  119. * // ...
  120. * }
  121. * })
  122. * ```
  123. * @param error - possible {@link NavigationFailure}
  124. * @param type - optional types to check for
  125. */
  126. export declare function isNavigationFailure(error: any, type?: ErrorTypes.NAVIGATION_GUARD_REDIRECT): error is NavigationRedirectError;
  127. export declare function isNavigationFailure(error: any, type?: ErrorTypes | NavigationFailureType): error is NavigationFailure;
  128. declare type Lazy<T> = () => Promise<T>;
  129. declare interface LocationAsName {
  130. name: RouteRecordName;
  131. params?: RouteParams;
  132. }
  133. /**
  134. * @internal
  135. */
  136. export declare interface LocationAsPath {
  137. path: string;
  138. }
  139. declare interface LocationAsRelative {
  140. params?: RouteParams;
  141. }
  142. /**
  143. * @internal
  144. */
  145. export declare interface LocationAsRelativeRaw {
  146. name?: RouteRecordName;
  147. params?: RouteParamsRaw;
  148. }
  149. /**
  150. * Normalized query object that appears in {@link RouteLocationNormalized}
  151. *
  152. * @public
  153. */
  154. export declare type LocationQuery = Record<string, LocationQueryValue | LocationQueryValue[]>;
  155. /**
  156. * Loose {@link LocationQuery} object that can be passed to functions like
  157. * {@link Router.push} and {@link Router.replace} or anywhere when creating a
  158. * {@link RouteLocationRaw}
  159. *
  160. * @public
  161. */
  162. export declare type LocationQueryRaw = Record<string | number, LocationQueryValueRaw | LocationQueryValueRaw[]>;
  163. /**
  164. * Possible values in normalized {@link LocationQuery}. `null` renders the query
  165. * param but without an `=`.
  166. *
  167. * @example
  168. * ```
  169. * ?isNull&isEmpty=&other=other
  170. * gives
  171. * `{ isNull: null, isEmpty: '', other: 'other' }`.
  172. * ```
  173. *
  174. * @internal
  175. */
  176. export declare type LocationQueryValue = string | null;
  177. /**
  178. * Possible values when defining a query.
  179. *
  180. * @internal
  181. */
  182. export declare type LocationQueryValueRaw = LocationQueryValue | number | undefined;
  183. /**
  184. * RouteRecord being rendered by the closest ancestor Router View. Used for
  185. * `onBeforeRouteUpdate` and `onBeforeRouteLeave`. rvlm stands for Router View
  186. * Location Matched
  187. *
  188. * @internal
  189. */
  190. export declare const matchedRouteKey: InjectionKey<ComputedRef<RouteRecordNormalized | undefined>>;
  191. declare interface MatcherLocation extends Pick<RouteLocation, 'name' | 'path' | 'params' | 'matched' | 'meta'> {
  192. }
  193. declare type MatcherLocationRaw = LocationAsPath | LocationAsName | LocationAsRelative;
  194. declare interface NavigationCallback {
  195. (to: HistoryLocation, from: HistoryLocation, information: NavigationInformation): void;
  196. }
  197. declare enum NavigationDirection {
  198. back = "back",
  199. forward = "forward",
  200. unknown = ""
  201. }
  202. /**
  203. * Extended Error that contains extra information regarding a failed navigation.
  204. */
  205. export declare interface NavigationFailure extends Error {
  206. /**
  207. * Type of the navigation. One of {@link NavigationFailureType}
  208. */
  209. type: ErrorTypes.NAVIGATION_CANCELLED | ErrorTypes.NAVIGATION_ABORTED | ErrorTypes.NAVIGATION_DUPLICATED;
  210. /**
  211. * Route location we were navigating from
  212. */
  213. from: RouteLocationNormalized;
  214. /**
  215. * Route location we were navigating to
  216. */
  217. to: RouteLocationNormalized;
  218. }
  219. /**
  220. * Enumeration with all possible types for navigation failures. Can be passed to
  221. * {@link isNavigationFailure} to check for specific failures.
  222. */
  223. export declare enum NavigationFailureType {
  224. /**
  225. * An aborted navigation is a navigation that failed because a navigation
  226. * guard returned `false` or called `next(false)`
  227. */
  228. aborted = 4,
  229. /**
  230. * A cancelled navigation is a navigation that failed because a more recent
  231. * navigation finished started (not necessarily finished).
  232. */
  233. cancelled = 8,
  234. /**
  235. * A duplicated navigation is a navigation that failed because it was
  236. * initiated while already being at the exact same location.
  237. */
  238. duplicated = 16
  239. }
  240. /**
  241. * Navigation guard. See [Navigation
  242. * Guards](/guide/advanced/navigation-guards.md).
  243. */
  244. export declare interface NavigationGuard {
  245. (to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): NavigationGuardReturn | Promise<NavigationGuardReturn>;
  246. }
  247. export declare interface NavigationGuardNext {
  248. (): void;
  249. (error: Error): void;
  250. (location: RouteLocationRaw): void;
  251. (valid: boolean | undefined): void;
  252. (cb: NavigationGuardNextCallback): void;
  253. }
  254. declare type NavigationGuardNextCallback = (vm: ComponentPublicInstance) => any;
  255. declare type NavigationGuardReturn = void | Error | RouteLocationRaw | boolean | NavigationGuardNextCallback;
  256. /**
  257. * {@inheritDoc NavigationGuard}
  258. */
  259. export declare interface NavigationGuardWithThis<T> {
  260. (this: T, to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext): NavigationGuardReturn | Promise<NavigationGuardReturn>;
  261. }
  262. export declare interface NavigationHookAfter {
  263. (to: RouteLocationNormalized, from: RouteLocationNormalized, failure?: NavigationFailure | void): any;
  264. }
  265. declare interface NavigationInformation {
  266. type: NavigationType_2;
  267. direction: NavigationDirection;
  268. delta: number;
  269. }
  270. declare interface NavigationRedirectError extends Omit<NavigationFailure, 'to' | 'type'> {
  271. type: ErrorTypes.NAVIGATION_GUARD_REDIRECT;
  272. to: RouteLocationRaw;
  273. }
  274. declare enum NavigationType_2 {
  275. pop = "pop",
  276. push = "push"
  277. }
  278. /**
  279. * Add a navigation guard that triggers whenever the component for the current
  280. * location is about to be left. Similar to {@link beforeRouteLeave} but can be
  281. * used in any component. The guard is removed when the component is unmounted.
  282. *
  283. * @param leaveGuard - {@link NavigationGuard}
  284. */
  285. export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void;
  286. /**
  287. * Add a navigation guard that triggers whenever the current location is about
  288. * to be updated. Similar to {@link beforeRouteUpdate} but can be used in any
  289. * component. The guard is removed when the component is unmounted.
  290. *
  291. * @param updateGuard - {@link NavigationGuard}
  292. */
  293. export declare function onBeforeRouteUpdate(updateGuard: NavigationGuard): void;
  294. /**
  295. * Transforms a queryString into a {@link LocationQuery} object. Accept both, a
  296. * version with the leading `?` and without Should work as URLSearchParams
  297. * @internal
  298. *
  299. * @param search - search string to parse
  300. * @returns a query object
  301. */
  302. export declare function parseQuery(search: string): LocationQuery;
  303. declare type PathParams = Record<string, string | string[]>;
  304. declare interface PathParser {
  305. /**
  306. * The regexp used to match a url
  307. */
  308. re: RegExp;
  309. /**
  310. * The score of the parser
  311. */
  312. score: Array<number[]>;
  313. /**
  314. * Keys that appeared in the path
  315. */
  316. keys: PathParserParamKey[];
  317. /**
  318. * Parses a url and returns the matched params or nul if it doesn't match. An
  319. * optional param that isn't preset will be an empty string. A repeatable
  320. * param will be an array if there is at least one value.
  321. *
  322. * @param path - url to parse
  323. * @returns a Params object, empty if there are no params. `null` if there is
  324. * no match
  325. */
  326. parse(path: string): PathParams | null;
  327. /**
  328. * Creates a string version of the url
  329. *
  330. * @param params - object of params
  331. * @returns a url
  332. */
  333. stringify(params: PathParams): string;
  334. }
  335. export declare type PathParserOptions = Pick<_PathParserOptions, 'end' | 'sensitive' | 'strict'>;
  336. /**
  337. * @internal
  338. */
  339. export declare interface _PathParserOptions {
  340. /**
  341. * Makes the RegExp case sensitive. Defaults to false
  342. */
  343. sensitive?: boolean;
  344. /**
  345. * Should we disallow a trailing slash. Defaults to false
  346. */
  347. strict?: boolean;
  348. /**
  349. * Should the RegExp match from the beginning by prepending a `^` to it. Defaults to true
  350. * @internal
  351. */
  352. start?: boolean;
  353. /**
  354. * Should the RegExp match until the end by appending a `$` to it. Defaults to true
  355. */
  356. end?: boolean;
  357. }
  358. /**
  359. * A param in a url like `/users/:id`
  360. */
  361. declare interface PathParserParamKey {
  362. name: string;
  363. repeatable: boolean;
  364. optional: boolean;
  365. }
  366. /**
  367. * Allowed Component definitions in route records provided by the user
  368. */
  369. declare type RawRouteComponent = RouteComponent | Lazy<RouteComponent>;
  370. /**
  371. * Allowed Component in {@link RouteLocationMatched}
  372. */
  373. export declare type RouteComponent = Component;
  374. /**
  375. * {@link RouteLocationRaw} resolved using the matcher
  376. */
  377. export declare interface RouteLocation extends _RouteLocationBase {
  378. /**
  379. * Array of {@link RouteRecord} containing components as they were
  380. * passed when adding records. It can also contain redirect records. This
  381. * can't be used directly
  382. */
  383. matched: RouteRecord[];
  384. }
  385. /**
  386. * Base properties for a normalized route location.
  387. *
  388. * @internal
  389. */
  390. export declare interface _RouteLocationBase {
  391. /**
  392. * Percentage encoded pathname section of the URL.
  393. */
  394. path: string;
  395. /**
  396. * The whole location including the `search` and `hash`. This string is
  397. * percentage encoded.
  398. */
  399. fullPath: string;
  400. /**
  401. * Object representation of the `search` property of the current location.
  402. */
  403. query: LocationQuery;
  404. /**
  405. * Hash of the current location. If present, starts with a `#`.
  406. */
  407. hash: string;
  408. /**
  409. * Name of the matched record
  410. */
  411. name: RouteRecordName | null | undefined;
  412. /**
  413. * Object of decoded params extracted from the `path`.
  414. */
  415. params: RouteParams;
  416. /**
  417. * Contains the location we were initially trying to access before ending up
  418. * on the current location.
  419. */
  420. redirectedFrom: RouteLocation | undefined;
  421. /**
  422. * Merged `meta` properties from all of the matched route records.
  423. */
  424. meta: RouteMeta;
  425. }
  426. /**
  427. * Allows overriding the current route returned by `useRoute` in tests. rl
  428. * stands for route location
  429. *
  430. * @internal
  431. */
  432. export declare const routeLocationKey: InjectionKey<RouteLocationNormalizedLoaded>;
  433. export declare interface RouteLocationMatched extends RouteRecordNormalized {
  434. components: Record<string, RouteComponent>;
  435. }
  436. /**
  437. * Similar to {@link RouteLocation} but its
  438. * {@link RouteLocationNormalized.matched} cannot contain redirect records
  439. */
  440. export declare interface RouteLocationNormalized extends _RouteLocationBase {
  441. /**
  442. * Array of {@link RouteRecordNormalized}
  443. */
  444. matched: RouteRecordNormalized[];
  445. }
  446. /**
  447. * {@link RouteLocationRaw} with
  448. */
  449. export declare interface RouteLocationNormalizedLoaded extends _RouteLocationBase {
  450. /**
  451. * Array of {@link RouteLocationMatched} containing only plain components (any
  452. * lazy-loaded components have been loaded and were replaced inside of the
  453. * `components` object) so it can be directly used to display routes. It
  454. * cannot contain redirect records either
  455. */
  456. matched: RouteLocationMatched[];
  457. }
  458. export declare interface RouteLocationOptions {
  459. /**
  460. * Replace the entry in the history instead of pushing a new entry
  461. */
  462. replace?: boolean;
  463. /**
  464. * Triggers the navigation even if the location is the same as the current one
  465. */
  466. force?: boolean;
  467. /**
  468. * State to save using the History API. This cannot contain any reactive
  469. * values and some primitives like Symbols are forbidden. More info at
  470. * https://developer.mozilla.org/en-US/docs/Web/API/History/state
  471. */
  472. state?: HistoryState;
  473. }
  474. /**
  475. * User-level route location
  476. */
  477. export declare type RouteLocationRaw = string | (RouteQueryAndHash & LocationAsPath & RouteLocationOptions) | (RouteQueryAndHash & LocationAsRelativeRaw & RouteLocationOptions);
  478. /**
  479. * Interface to type `meta` fields in route records.
  480. *
  481. * @example
  482. *
  483. * ```ts
  484. * // typings.d.ts or router.ts
  485. * import 'vue-router';
  486. *
  487. * declare module 'vue-router' {
  488. * interface RouteMeta {
  489. * requiresAuth?: boolean
  490. * }
  491. * }
  492. * ```
  493. */
  494. export declare interface RouteMeta extends Record<string | number | symbol, unknown> {
  495. }
  496. export declare type RouteParams = Record<string, RouteParamValue | RouteParamValue[]>;
  497. export declare type RouteParamsRaw = Record<string, RouteParamValueRaw | Exclude<RouteParamValueRaw, null | undefined>[]>;
  498. /**
  499. * @internal
  500. */
  501. export declare type RouteParamValue = string;
  502. /**
  503. * @internal
  504. */
  505. export declare type RouteParamValueRaw = RouteParamValue | number | null | undefined;
  506. /**
  507. * @internal
  508. */
  509. export declare interface RouteQueryAndHash {
  510. query?: LocationQueryRaw;
  511. hash?: string;
  512. }
  513. /**
  514. * Router instance
  515. */
  516. export declare interface Router {
  517. /**
  518. * @internal
  519. */
  520. /**
  521. * Current {@link RouteLocationNormalized}
  522. */
  523. readonly currentRoute: Ref<RouteLocationNormalizedLoaded>;
  524. /**
  525. * Original options object passed to create the Router
  526. */
  527. readonly options: RouterOptions;
  528. /**
  529. * Add a new {@link RouteRecordRaw route record} as the child of an existing route.
  530. *
  531. * @param parentName - Parent Route Record where `route` should be appended at
  532. * @param route - Route Record to add
  533. */
  534. addRoute(parentName: RouteRecordName, route: RouteRecordRaw): () => void;
  535. /**
  536. * Add a new {@link RouteRecordRaw route record} to the router.
  537. *
  538. * @param route - Route Record to add
  539. */
  540. addRoute(route: RouteRecordRaw): () => void;
  541. /**
  542. * Remove an existing route by its name.
  543. *
  544. * @param name - Name of the route to remove
  545. */
  546. removeRoute(name: RouteRecordName): void;
  547. /**
  548. * Checks if a route with a given name exists
  549. *
  550. * @param name - Name of the route to check
  551. */
  552. hasRoute(name: RouteRecordName): boolean;
  553. /**
  554. * Get a full list of all the {@link RouteRecord route records}.
  555. */
  556. getRoutes(): RouteRecord[];
  557. /**
  558. * Returns the {@link RouteLocation normalized version} of a
  559. * {@link RouteLocationRaw route location}. Also includes an `href` property
  560. * that includes any existing `base`. By default the `currentLocation` used is
  561. * `route.currentRoute` and should only be overriden in advanced use cases.
  562. *
  563. * @param to - Raw route location to resolve
  564. * @param currentLocation - Optional current location to resolve against
  565. */
  566. resolve(to: RouteLocationRaw, currentLocation?: RouteLocationNormalizedLoaded): RouteLocation & {
  567. href: string;
  568. };
  569. /**
  570. * Programmatically navigate to a new URL by pushing an entry in the history
  571. * stack.
  572. *
  573. * @param to - Route location to navigate to
  574. */
  575. push(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>;
  576. /**
  577. * Programmatically navigate to a new URL by replacing the current entry in
  578. * the history stack.
  579. *
  580. * @param to - Route location to navigate to
  581. */
  582. replace(to: RouteLocationRaw): Promise<NavigationFailure | void | undefined>;
  583. /**
  584. * Go back in history if possible by calling `history.back()`. Equivalent to
  585. * `router.go(-1)`.
  586. */
  587. back(): ReturnType<Router['go']>;
  588. /**
  589. * Go forward in history if possible by calling `history.forward()`.
  590. * Equivalent to `router.go(1)`.
  591. */
  592. forward(): ReturnType<Router['go']>;
  593. /**
  594. * Allows you to move forward or backward through the history. Calls
  595. * `history.go()`.
  596. *
  597. * @param delta - The position in the history to which you want to move,
  598. * relative to the current page
  599. */
  600. go(delta: number): void;
  601. /**
  602. * Add a navigation guard that executes before any navigation. Returns a
  603. * function that removes the registered guard.
  604. *
  605. * @param guard - navigation guard to add
  606. */
  607. beforeEach(guard: NavigationGuardWithThis<undefined>): () => void;
  608. /**
  609. * Add a navigation guard that executes before navigation is about to be
  610. * resolved. At this state all component have been fetched and other
  611. * navigation guards have been successful. Returns a function that removes the
  612. * registered guard.
  613. *
  614. * @example
  615. * ```js
  616. * router.beforeResolve(to => {
  617. * if (to.meta.requiresAuth && !isAuthenticated) return false
  618. * })
  619. * ```
  620. *
  621. * @param guard - navigation guard to add
  622. */
  623. beforeResolve(guard: NavigationGuardWithThis<undefined>): () => void;
  624. /**
  625. * Add a navigation hook that is executed after every navigation. Returns a
  626. * function that removes the registered hook.
  627. *
  628. * @example
  629. * ```js
  630. * router.afterEach((to, from, failure) => {
  631. * if (isNavigationFailure(failure)) {
  632. * console.log('failed navigation', failure)
  633. * }
  634. * })
  635. * ```
  636. *
  637. * @param guard - navigation hook to add
  638. */
  639. afterEach(guard: NavigationHookAfter): () => void;
  640. /**
  641. * Adds an error handler that is called every time a non caught error happens
  642. * during navigation. This includes errors thrown synchronously and
  643. * asynchronously, errors returned or passed to `next` in any navigation
  644. * guard, and errors occurred when trying to resolve an async component that
  645. * is required to render a route.
  646. *
  647. * @param handler - error handler to register
  648. */
  649. onError(handler: _ErrorHandler): () => void;
  650. /**
  651. * Returns a Promise that resolves when the router has completed the initial
  652. * navigation, which means it has resolved all async enter hooks and async
  653. * components that are associated with the initial route. If the initial
  654. * navigation already happened, the promise resolves immediately.
  655. *
  656. * This is useful in server-side rendering to ensure consistent output on both
  657. * the server and the client. Note that on server side, you need to manually
  658. * push the initial location while on client side, the router automatically
  659. * picks it up from the URL.
  660. */
  661. isReady(): Promise<void>;
  662. /**
  663. * Called automatically by `app.use(router)`. Should not be called manually by
  664. * the user.
  665. *
  666. * @internal
  667. * @param app - Application that uses the router
  668. */
  669. install(app: App): void;
  670. }
  671. /**
  672. * {@inheritDoc RouteRecordNormalized}
  673. */
  674. export declare type RouteRecord = RouteRecordNormalized;
  675. /**
  676. * Common properties among all kind of {@link RouteRecordRaw}
  677. * @internal
  678. */
  679. export declare interface _RouteRecordBase extends PathParserOptions {
  680. /**
  681. * Path of the record. Should start with `/` unless the record is the child of
  682. * another record.
  683. *
  684. * @example `/users/:id` matches `/users/1` as well as `/users/posva`.
  685. */
  686. path: string;
  687. /**
  688. * Where to redirect if the route is directly matched. The redirection happens
  689. * before any navigation guard and triggers a new navigation with the new
  690. * target location.
  691. */
  692. redirect?: RouteRecordRedirectOption;
  693. /**
  694. * Array of nested routes.
  695. */
  696. children?: RouteRecordRaw[];
  697. /**
  698. * Aliases for the record. Allows defining extra paths that will behave like a
  699. * copy of the record. Allows having paths shorthands like `/users/:id` and
  700. * `/u/:id`. All `alias` and `path` values must share the same params.
  701. */
  702. alias?: string | string[];
  703. /**
  704. * Name for the route record.
  705. */
  706. name?: RouteRecordName;
  707. /**
  708. * Before Enter guard specific to this record. Note `beforeEnter` has no
  709. * effect if the record has a `redirect` property.
  710. */
  711. beforeEnter?: NavigationGuardWithThis<undefined> | NavigationGuardWithThis<undefined>[];
  712. /**
  713. * Arbitrary data attached to the record.
  714. */
  715. meta?: RouteMeta;
  716. }
  717. declare interface RouteRecordMatcher extends PathParser {
  718. record: RouteRecord;
  719. parent: RouteRecordMatcher | undefined;
  720. children: RouteRecordMatcher[];
  721. alias: RouteRecordMatcher[];
  722. }
  723. /**
  724. * Route Record defining multiple named components with the `components` option.
  725. */
  726. declare interface RouteRecordMultipleViews extends _RouteRecordBase {
  727. /**
  728. * Components to display when the URL matches this route. Allow using named views.
  729. */
  730. components: Record<string, RawRouteComponent>;
  731. component?: never;
  732. /**
  733. * Allow passing down params as props to the component rendered by
  734. * `router-view`. Should be an object with the same keys as `components` or a
  735. * boolean to be applied to every component.
  736. */
  737. props?: Record<string, _RouteRecordProps> | boolean;
  738. }
  739. /**
  740. * Possible values for a user-defined route record's name
  741. */
  742. export declare type RouteRecordName = string | symbol;
  743. /**
  744. * Normalized version of a {@link RouteRecord route record}
  745. */
  746. export declare interface RouteRecordNormalized {
  747. /**
  748. * {@inheritDoc _RouteRecordBase.path}
  749. */
  750. path: _RouteRecordBase['path'];
  751. /**
  752. * {@inheritDoc _RouteRecordBase.redirect}
  753. */
  754. redirect: _RouteRecordBase['redirect'] | undefined;
  755. /**
  756. * {@inheritDoc _RouteRecordBase.name}
  757. */
  758. name: _RouteRecordBase['name'];
  759. /**
  760. * {@inheritDoc RouteRecordMultipleViews.components}
  761. */
  762. components: RouteRecordMultipleViews['components'];
  763. /**
  764. * {@inheritDoc _RouteRecordBase.components}
  765. */
  766. children: Exclude<_RouteRecordBase['children'], void>;
  767. /**
  768. * {@inheritDoc _RouteRecordBase.meta}
  769. */
  770. meta: Exclude<_RouteRecordBase['meta'], void>;
  771. /**
  772. * {@inheritDoc RouteRecordMultipleViews.props}
  773. */
  774. props: Record<string, _RouteRecordProps>;
  775. /**
  776. * Registered beforeEnter guards
  777. */
  778. beforeEnter: _RouteRecordBase['beforeEnter'];
  779. /**
  780. * Registered leave guards
  781. *
  782. * @internal
  783. */
  784. leaveGuards: Set<NavigationGuard>;
  785. /**
  786. * Registered update guards
  787. *
  788. * @internal
  789. */
  790. updateGuards: Set<NavigationGuard>;
  791. /**
  792. * Registered beforeRouteEnter callbacks passed to `next` or returned in guards
  793. *
  794. * @internal
  795. */
  796. enterCallbacks: Record<string, NavigationGuardNextCallback[]>;
  797. /**
  798. * Mounted route component instances
  799. * Having the instances on the record mean beforeRouteUpdate and
  800. * beforeRouteLeave guards can only be invoked with the latest mounted app
  801. * instance if there are multiple application instances rendering the same
  802. * view, basically duplicating the content on the page, which shouldn't happen
  803. * in practice. It will work if multiple apps are rendering different named
  804. * views.
  805. */
  806. instances: Record<string, ComponentPublicInstance | undefined | null>;
  807. /**
  808. * Defines if this record is the alias of another one. This property is
  809. * `undefined` if the record is the original one.
  810. */
  811. aliasOf: RouteRecordNormalized | undefined;
  812. }
  813. /**
  814. * @internal
  815. */
  816. declare type _RouteRecordProps = boolean | Record<string, any> | ((to: RouteLocationNormalized) => Record<string, any>);
  817. export declare type RouteRecordRaw = RouteRecordSingleView | RouteRecordMultipleViews | RouteRecordRedirect;
  818. /**
  819. * Route Record that defines a redirect. Cannot have `component` or `components`
  820. * as it is never rendered.
  821. */
  822. declare interface RouteRecordRedirect extends _RouteRecordBase {
  823. redirect: RouteRecordRedirectOption;
  824. component?: never;
  825. components?: never;
  826. }
  827. /**
  828. * @internal
  829. */
  830. export declare type RouteRecordRedirectOption = RouteLocationRaw | ((to: RouteLocation) => RouteLocationRaw);
  831. /**
  832. * Route Record defining one single component with the `component` option.
  833. */
  834. declare interface RouteRecordSingleView extends _RouteRecordBase {
  835. /**
  836. * Component to display when the URL matches this route.
  837. */
  838. component: RawRouteComponent;
  839. components?: never;
  840. /**
  841. * Allow passing down params as props to the component rendered by `router-view`.
  842. */
  843. props?: _RouteRecordProps;
  844. }
  845. /**
  846. * Interface implemented by History implementations that can be passed to the
  847. * router as {@link Router.history}
  848. *
  849. * @alpha
  850. */
  851. export declare interface RouterHistory {
  852. /**
  853. * Base path that is prepended to every url. This allows hosting an SPA at a
  854. * subfolder of a domain like `example.com/subfolder` by having a `base` of
  855. * `/subfolder`
  856. */
  857. readonly base: string;
  858. /**
  859. * Current History location
  860. */
  861. readonly location: HistoryLocation;
  862. /**
  863. * Current History state
  864. */
  865. readonly state: HistoryState;
  866. /**
  867. * Navigates to a location. In the case of an HTML5 History implementation,
  868. * this will call `history.pushState` to effectively change the URL.
  869. *
  870. * @param to - location to push
  871. * @param data - optional {@link HistoryState} to be associated with the
  872. * navigation entry
  873. */
  874. push(to: HistoryLocation, data?: HistoryState): void;
  875. /**
  876. * Same as {@link RouterHistory.push} but performs a `history.replaceState`
  877. * instead of `history.pushState`
  878. *
  879. * @param to - location to set
  880. * @param data - optional {@link HistoryState} to be associated with the
  881. * navigation entry
  882. */
  883. replace(to: HistoryLocation, data?: HistoryState): void;
  884. /**
  885. * Traverses history in a given direction.
  886. *
  887. * @example
  888. * ```js
  889. * myHistory.go(-1) // equivalent to window.history.back()
  890. * myHistory.go(1) // equivalent to window.history.forward()
  891. * ```
  892. *
  893. * @param delta - distance to travel. If delta is \< 0, it will go back,
  894. * if it's \> 0, it will go forward by that amount of entries.
  895. * @param triggerListeners - whether this should trigger listeners attached to
  896. * the history
  897. */
  898. go(delta: number, triggerListeners?: boolean): void;
  899. /**
  900. * Attach a listener to the History implementation that is triggered when the
  901. * navigation is triggered from outside (like the Browser back and forward
  902. * buttons) or when passing `true` to {@link RouterHistory.back} and
  903. * {@link RouterHistory.forward}
  904. *
  905. * @param callback - listener to attach
  906. * @returns a callback to remove the listener
  907. */
  908. listen(callback: NavigationCallback): () => void;
  909. /**
  910. * Generates the corresponding href to be used in an anchor tag.
  911. *
  912. * @param location - history location that should create an href
  913. */
  914. createHref(location: HistoryLocation): string;
  915. /**
  916. * Clears any event listener attached by the history implementation.
  917. */
  918. destroy(): void;
  919. }
  920. /**
  921. * Allows overriding the router instance returned by `useRouter` in tests. r
  922. * stands for router
  923. *
  924. * @internal
  925. */
  926. export declare const routerKey: InjectionKey<Router>;
  927. /**
  928. * Component to render a link that triggers a navigation on click.
  929. */
  930. export declare const RouterLink: {
  931. new (): {
  932. $props: AllowedComponentProps & ComponentCustomProps & VNodeProps & RouterLinkProps;
  933. $slots: {
  934. default: (arg: UnwrapRef<ReturnType<typeof useLink>>) => VNode[];
  935. };
  936. };
  937. /**
  938. * Access to `useLink()` without depending on using vue-router
  939. *
  940. * @internal
  941. */
  942. useLink: typeof useLink;
  943. };
  944. declare interface RouterLinkOptions {
  945. /**
  946. * Route Location the link should navigate to when clicked on.
  947. */
  948. to: RouteLocationRaw;
  949. /**
  950. * Calls `router.replace` instead of `router.push`.
  951. */
  952. replace?: boolean;
  953. }
  954. export declare interface RouterLinkProps extends RouterLinkOptions {
  955. /**
  956. * Whether RouterLink should not wrap its content in an `a` tag. Useful when
  957. * using `v-slot` to create a custom RouterLink
  958. */
  959. custom?: boolean;
  960. /**
  961. * Class to apply when the link is active
  962. */
  963. activeClass?: string;
  964. /**
  965. * Class to apply when the link is exact active
  966. */
  967. exactActiveClass?: string;
  968. /**
  969. * Value passed to the attribute `aria-current` when the link is exact active. Defaults to "page"
  970. */
  971. ariaCurrentValue?: 'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false';
  972. }
  973. /**
  974. * Internal RouterMatcher
  975. *
  976. * @internal
  977. */
  978. export declare interface RouterMatcher {
  979. addRoute: (record: RouteRecordRaw, parent?: RouteRecordMatcher) => () => void;
  980. removeRoute: {
  981. (matcher: RouteRecordMatcher): void;
  982. (name: RouteRecordName): void;
  983. };
  984. getRoutes: () => RouteRecordMatcher[];
  985. getRecordMatcher: (name: RouteRecordName) => RouteRecordMatcher | undefined;
  986. /**
  987. * Resolves a location. Gives access to the route record that corresponds to the actual path as well as filling the corresponding params objects
  988. *
  989. * @param location - MatcherLocationRaw to resolve to a url
  990. * @param currentLocation - MatcherLocation of the current location
  991. */
  992. resolve: (location: MatcherLocationRaw, currentLocation: MatcherLocation) => MatcherLocation;
  993. }
  994. /**
  995. * Options to initialize a {@link Router} instance.
  996. */
  997. export declare interface RouterOptions extends PathParserOptions {
  998. /**
  999. * History implementation used by the router. Most web applications should use
  1000. * `createWebHistory` but it requires the server to be properly configured.
  1001. * You can also use a _hash_ based history with `createWebHashHistory` that
  1002. * does not require any configuration on the server but isn't handled at all
  1003. * by search engines and does poorly on SEO.
  1004. *
  1005. * @example
  1006. * ```js
  1007. * createRouter({
  1008. * history: createWebHistory(),
  1009. * // other options...
  1010. * })
  1011. * ```
  1012. */
  1013. history: RouterHistory;
  1014. /**
  1015. * Initial list of routes that should be added to the router.
  1016. */
  1017. routes: RouteRecordRaw[];
  1018. /**
  1019. * Function to control scrolling when navigating between pages. Can return a
  1020. * Promise to delay scrolling. Check {@link ScrollBehavior}.
  1021. *
  1022. * @example
  1023. * ```js
  1024. * function scrollBehavior(to, from, savedPosition) {
  1025. * // `to` and `from` are both route locations
  1026. * // `savedPosition` can be null if there isn't one
  1027. * }
  1028. * ```
  1029. */
  1030. scrollBehavior?: RouterScrollBehavior;
  1031. /**
  1032. * Custom implementation to parse a query. See its counterpart,
  1033. * {@link RouterOptions.stringifyQuery}.
  1034. *
  1035. * @example
  1036. * Let's say you want to use the package {@link https://github.com/ljharb/qs | qs}
  1037. * to parse queries, you can provide both `parseQuery` and `stringifyQuery`:
  1038. * ```js
  1039. * import qs from 'qs'
  1040. *
  1041. * createRouter({
  1042. * // other options...
  1043. * parseQuery: qs.parse,
  1044. * stringifyQuery: qs.stringify,
  1045. * })
  1046. * ```
  1047. */
  1048. parseQuery?: typeof parseQuery;
  1049. /**
  1050. * Custom implementation to stringify a query object. Should not prepend a leading `?`.
  1051. * {@link RouterOptions.parseQuery | parseQuery} counterpart to handle query parsing.
  1052. */
  1053. stringifyQuery?: typeof stringifyQuery;
  1054. /**
  1055. * Default class applied to active {@link RouterLink}. If none is provided,
  1056. * `router-link-active` will be applied.
  1057. */
  1058. linkActiveClass?: string;
  1059. /**
  1060. * Default class applied to exact active {@link RouterLink}. If none is provided,
  1061. * `router-link-exact-active` will be applied.
  1062. */
  1063. linkExactActiveClass?: string;
  1064. }
  1065. /**
  1066. * Type of the `scrollBehavior` option that can be passed to `createRouter`.
  1067. */
  1068. export declare interface RouterScrollBehavior {
  1069. /**
  1070. * @param to - Route location where we are navigating to
  1071. * @param from - Route location where we are navigating from
  1072. * @param savedPosition - saved position if it exists, `null` otherwise
  1073. */
  1074. (to: RouteLocationNormalized, from: RouteLocationNormalizedLoaded, savedPosition: _ScrollPositionNormalized | null): Awaitable<ScrollPosition | false | void>;
  1075. }
  1076. /**
  1077. * Component to display the current route the user is at.
  1078. */
  1079. export declare const RouterView: new () => {
  1080. $props: AllowedComponentProps & ComponentCustomProps & VNodeProps & RouterViewProps;
  1081. $slots: {
  1082. default: (arg: {
  1083. Component: VNode;
  1084. route: RouteLocationNormalizedLoaded;
  1085. }) => VNode[];
  1086. };
  1087. };
  1088. /**
  1089. * Allows overriding the current route used by router-view. Internally this is
  1090. * used when the `route` prop is passed.
  1091. *
  1092. * @internal
  1093. */
  1094. export declare const routerViewLocationKey: InjectionKey<Ref<RouteLocationNormalizedLoaded>>;
  1095. export declare interface RouterViewProps {
  1096. name?: string;
  1097. route?: RouteLocationNormalized;
  1098. }
  1099. declare type ScrollPosition = ScrollPositionCoordinates | ScrollPositionElement;
  1100. /**
  1101. * Scroll position similar to
  1102. * {@link https://developer.mozilla.org/en-US/docs/Web/API/ScrollToOptions | `ScrollToOptions`}.
  1103. * Note that not all browsers support `behavior`.
  1104. */
  1105. declare type ScrollPositionCoordinates = {
  1106. behavior?: ScrollOptions['behavior'];
  1107. left?: number;
  1108. top?: number;
  1109. };
  1110. declare interface ScrollPositionElement extends ScrollToOptions {
  1111. /**
  1112. * A valid CSS selector. Note some characters must be escaped in id selectors (https://mathiasbynens.be/notes/css-escapes).
  1113. * @example
  1114. * Here are a few examples:
  1115. *
  1116. * - `.title`
  1117. * - `.content:first-child`
  1118. * - `#marker`
  1119. * - `#marker\~with\~symbols`
  1120. * - `#marker.with.dot`: selects `class="with dot" id="marker"`, not `id="marker.with.dot"`
  1121. *
  1122. */
  1123. el: string | Element;
  1124. }
  1125. /**
  1126. * Internal normalized version of {@link ScrollPositionCoordinates} that always
  1127. * has `left` and `top` coordinates.
  1128. *
  1129. * @internal
  1130. */
  1131. declare type _ScrollPositionNormalized = {
  1132. behavior?: ScrollOptions['behavior'];
  1133. left: number;
  1134. top: number;
  1135. };
  1136. /**
  1137. * Initial route location where the router is. Can be used in navigation guards
  1138. * to differentiate the initial navigation.
  1139. *
  1140. * @example
  1141. * ```js
  1142. * import { START_LOCATION } from 'vue-router'
  1143. *
  1144. * router.beforeEach((to, from) => {
  1145. * if (from === START_LOCATION) {
  1146. * // initial navigation
  1147. * }
  1148. * })
  1149. * ```
  1150. */
  1151. export declare const START_LOCATION: RouteLocationNormalizedLoaded;
  1152. /**
  1153. * Stringifies a {@link LocationQueryRaw} object. Like `URLSearchParams`, it
  1154. * doesn't prepend a `?`
  1155. *
  1156. * @internal
  1157. *
  1158. * @param query - query object to stringify
  1159. * @returns string version of the query without the leading `?`
  1160. */
  1161. export declare function stringifyQuery(query: LocationQueryRaw): string;
  1162. export declare function useLink(props: UseLinkOptions): {
  1163. route: ComputedRef<RouteLocation & {
  1164. href: string;
  1165. }>;
  1166. href: ComputedRef<string>;
  1167. isActive: ComputedRef<boolean>;
  1168. isExactActive: ComputedRef<boolean>;
  1169. navigate: (e?: MouseEvent) => Promise<void | NavigationFailure>;
  1170. };
  1171. export declare type UseLinkOptions = VueUseOptions<RouterLinkOptions>;
  1172. /**
  1173. * Returns the current route location. Equivalent to using `$route` inside
  1174. * templates.
  1175. */
  1176. export declare function useRoute(): RouteLocationNormalizedLoaded;
  1177. /**
  1178. * Returns the router instance. Equivalent to using `$router` inside
  1179. * templates.
  1180. */
  1181. export declare function useRouter(): Router;
  1182. /**
  1183. * Allows overriding the router view depth to control which component in
  1184. * `matched` is rendered. rvd stands for Router View Depth
  1185. *
  1186. * @internal
  1187. */
  1188. export declare const viewDepthKey: InjectionKey<number>;
  1189. /**
  1190. * Type to transform a static object into one that allows passing Refs as
  1191. * values.
  1192. * @internal
  1193. */
  1194. declare type VueUseOptions<T> = {
  1195. [k in keyof T]: Ref<T[k]> | T[k];
  1196. };
  1197. export { }
  1198. declare module '@vue/runtime-core' {
  1199. export interface ComponentCustomOptions {
  1200. /**
  1201. * Guard called when the router is navigating to the route that is rendering
  1202. * this component from a different route. Differently from `beforeRouteUpdate`
  1203. * and `beforeRouteLeave`, `beforeRouteEnter` does not have access to the
  1204. * component instance through `this` because it triggers before the component
  1205. * is even mounted.
  1206. *
  1207. * @param to - RouteLocationRaw we are navigating to
  1208. * @param from - RouteLocationRaw we are navigating from
  1209. * @param next - function to validate, cancel or modify (by redirecting) the
  1210. * navigation
  1211. */
  1212. beforeRouteEnter?: NavigationGuardWithThis<undefined>
  1213. /**
  1214. * Guard called whenever the route that renders this component has changed but
  1215. * it is reused for the new route. This allows you to guard for changes in
  1216. * params, the query or the hash.
  1217. *
  1218. * @param to - RouteLocationRaw we are navigating to
  1219. * @param from - RouteLocationRaw we are navigating from
  1220. * @param next - function to validate, cancel or modify (by redirecting) the
  1221. * navigation
  1222. */
  1223. beforeRouteUpdate?: NavigationGuard
  1224. /**
  1225. * Guard called when the router is navigating away from the current route that
  1226. * is rendering this component.
  1227. *
  1228. * @param to - RouteLocationRaw we are navigating to
  1229. * @param from - RouteLocationRaw we are navigating from
  1230. * @param next - function to validate, cancel or modify (by redirecting) the
  1231. * navigation
  1232. */
  1233. beforeRouteLeave?: NavigationGuard
  1234. }
  1235. export interface ComponentCustomProperties {
  1236. /**
  1237. * Normalized current location. See {@link RouteLocationNormalizedLoaded}.
  1238. */
  1239. $route: RouteLocationNormalizedLoaded
  1240. /**
  1241. * {@link Router} instance used by the application.
  1242. */
  1243. $router: Router
  1244. }
  1245. }