From: Eduardo San Martin Morote Date: Thu, 4 Aug 2022 12:17:34 +0000 (+0200) Subject: docs: api gen X-Git-Tag: v4.1.4~13 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=3fccbb746a5d12dc50e8f646194e60d30cb031f4;p=thirdparty%2Fvuejs%2Frouter.git docs: api gen --- diff --git a/packages/docs/api/enums/NavigationFailureType.md b/packages/docs/api/enums/NavigationFailureType.md new file mode 100644 index 00000000..675dc1db --- /dev/null +++ b/packages/docs/api/enums/NavigationFailureType.md @@ -0,0 +1,39 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationFailureType + +# Enumeration: NavigationFailureType + +Enumeration with all possible types for navigation failures. Can be passed to +[isNavigationFailure](../index.md#isnavigationfailure) to check for specific failures. + +## Enumeration Members + +### aborted + +• **aborted** = ``4`` + +An aborted navigation is a navigation that failed because a navigation +guard returned `false` or called `next(false)` + +___ + +### cancelled + +• **cancelled** = ``8`` + +A cancelled navigation is a navigation that failed because a more recent +navigation finished started (not necessarily finished). + +___ + +### duplicated + +• **duplicated** = ``16`` + +A duplicated navigation is a navigation that failed because it was +initiated while already being at the exact same location. diff --git a/packages/docs/api/index.md b/packages/docs/api/index.md index 2331a520..fbd21289 100644 --- a/packages/docs/api/index.md +++ b/packages/docs/api/index.md @@ -1,1126 +1,407 @@ --- -sidebar: auto +sidebar: "auto" +editLinks: false +sidebarDepth: 3 --- -# API Reference +# API Documentation -## `` Props +## Enumerations -### to +- [NavigationFailureType](enums/NavigationFailureType.md) -- **Type**: [`RouteLocationRaw`](#routelocationraw) -- **Details**: +## Interfaces - Denotes the target route of the link. When clicked, the value of the `to` prop will be passed to `router.push()` internally, so it can either be a `string` or a [route location object](#routelocationraw). +- [HistoryState](interfaces/HistoryState.md) +- [NavigationFailure](interfaces/NavigationFailure.md) +- [NavigationGuard](interfaces/NavigationGuard.md) +- [NavigationGuardNext](interfaces/NavigationGuardNext.md) +- [NavigationGuardWithThis](interfaces/NavigationGuardWithThis.md) +- [NavigationHookAfter](interfaces/NavigationHookAfter.md) +- [RouteLocation](interfaces/RouteLocation.md) +- [RouteLocationMatched](interfaces/RouteLocationMatched.md) +- [RouteLocationNormalized](interfaces/RouteLocationNormalized.md) +- [RouteLocationNormalizedLoaded](interfaces/RouteLocationNormalizedLoaded.md) +- [RouteLocationOptions](interfaces/RouteLocationOptions.md) +- [RouteMeta](interfaces/RouteMeta.md) +- [RouteRecordNormalized](interfaces/RouteRecordNormalized.md) +- [Router](interfaces/Router.md) +- [RouterHistory](interfaces/RouterHistory.md) +- [RouterLinkProps](interfaces/RouterLinkProps.md) +- [RouterOptions](interfaces/RouterOptions.md) +- [RouterScrollBehavior](interfaces/RouterScrollBehavior.md) +- [RouterViewProps](interfaces/RouterViewProps.md) -```html - -Home - -Home +## Type Aliases - -Home +### LocationQuery - -Home +Ƭ **LocationQuery**: `Record`<`string`, `LocationQueryValue` \| `LocationQueryValue`[]\> - -User +Normalized query object that appears in [RouteLocationNormalized](interfaces/RouteLocationNormalized.md) - - - Register - -``` - -### replace - -- **Type**: `boolean` -- **Default**: `false` -- **Details**: - - Setting `replace` prop will call `router.replace()` instead of `router.push()` when clicked, so the navigation will not leave a history record. - -```html - -``` - -### active-class - -- **Type**: `string` -- **Default**: `"router-link-active"` (or global [`linkActiveClass`](#linkactiveclass)) -- **Details**: - - Class to apply on the rendered `` when the link is active. - -### aria-current-value - -- **Type**: `'page' | 'step' | 'location' | 'date' | 'time' | 'true' | 'false'` (`string`) -- **Default**: `"page"` -- **Details**: +___ - Value passed to the attribute `aria-current` when the link is exactly active. +### LocationQueryRaw -### custom +Ƭ **LocationQueryRaw**: `Record`<`string` \| `number`, `LocationQueryValueRaw` \| `LocationQueryValueRaw`[]\> -- **Type**: `boolean` -- **Default**: `false` -- **Details**: +Loose [LocationQuery](index.md#locationquery) object that can be passed to functions like +[push](interfaces/Router.md#push) and [replace](interfaces/Router.md#replace) or anywhere when creating a +[RouteLocationRaw](index.md#routelocationraw) - Whether `` should not wrap its content in an `` element. Useful when using [`v-slot`](#router-link-s-v-slot) to create a custom RouterLink. By default, `` will render its content wrapped in an `` element, even when using `v-slot`. Passing the `custom` prop, removes that behavior. +___ -- **Examples**: +### PathParserOptions - ```html - - {{ route.fullPath }} - - ``` +Ƭ **PathParserOptions**: `Pick`<`_PathParserOptions`, ``"end"`` \| ``"sensitive"`` \| ``"strict"``\> - Renders `/home`. +___ - ```html - - {{ route.fullPath }} - - ``` +### RouteComponent - Renders `/home`. +Ƭ **RouteComponent**: `Component` \| `DefineComponent` -### exact-active-class +Allowed Component in [RouteLocationMatched](interfaces/RouteLocationMatched.md) -- **Type**: `string` -- **Default**: `"router-link-exact-active"` (or global [`linkExactActiveClass`](#linkexactactiveclass)) -- **Details**: +___ - Class to apply on the rendered `` when the link is exact active. +### RouteLocationRaw -## ``'s `v-slot` +Ƭ **RouteLocationRaw**: `string` \| `RouteLocationPathRaw` \| `RouteLocationNamedRaw` -`` exposes a low level customization through a [scoped slot](https://v3.vuejs.org/guide/component-slots.html#scoped-slots). 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. +User-level route location -:::tip -Remember to pass the `custom` option to `` to prevent it from wrapping its content inside of an `` element. -::: +___ -```html - - - {{ route.fullPath }} - - -``` +### RouteParams -- `href`: resolved url. This would be the `href` attribute of an `` element. It contains the `base` if any was provided. -- `route`: resolved normalized location. -- `navigate`: function to trigger the navigation. **It will automatically prevent events when necessary**, the same way `router-link` does, e.g. `ctrl` or `cmd` + click will still be ignored by `navigate`. -- `isActive`: `true` if the [active class](#active-class) should be applied. Allows to apply an arbitrary class. -- `isExactActive`: `true` if the [exact active class](#exact-active-class) should be applied. Allows to apply an arbitrary class. - -### Example: Applying Active Class to Outer Element - -Sometimes we may want the active class to be applied to an outer element rather than the `` element itself, in that case, you can wrap that element inside a `router-link` and use the `v-slot` properties to create your link: - -```html - -
  • - {{ route.fullPath }} -
  • - -``` +Ƭ **RouteParams**: `Record`<`string`, `RouteParamValue` \| `RouteParamValue`[]\> -:::tip -If you add a `target="_blank"` to your `a` element, you must omit the `@click="navigate"` handler. -::: +___ -## `` Props +### RouteParamsRaw -### name +Ƭ **RouteParamsRaw**: `Record`<`string`, `RouteParamValueRaw` \| `Exclude`<`RouteParamValueRaw`, ``null`` \| `undefined`\>[]\> -- **Type**: `string` -- **Default**: `"default"` -- **Details**: +___ - When a `` has a `name`, it will render the component with the corresponding name in the matched route record's `components` option. +### RouteRecord -- **See Also**: [Named Views](../guide/essentials/named-views.md) +Ƭ **RouteRecord**: [`RouteRecordNormalized`](interfaces/RouteRecordNormalized.md) -### route +Normalized version of a [route record](index.md#routerecord). -- **Type**: [`RouteLocationNormalized`](#routelocationnormalized) -- **Details**: +___ - A route location that has all of its component resolved (if any was lazy loaded) so it can be displayed. +### RouteRecordName -## ``'s `v-slot` +Ƭ **RouteRecordName**: `string` \| `symbol` -`` exposes a `v-slot` API mainly to wrap your route components with `` and `` components. +Possible values for a user-defined route record's name -```html - - - - - - - - - - -``` +___ -- `Component`: VNodes to be passed to a ``'s `is` prop. -- `route`: resolved normalized [route location](#routelocationnormalized). +### RouteRecordRaw -Note you should be passing View components' props directly to the `` rather than the ``: +Ƭ **RouteRecordRaw**: `RouteRecordSingleView` \| `RouteRecordSingleViewWithChildren` \| `RouteRecordMultipleViews` \| `RouteRecordMultipleViewsWithChildren` \| `RouteRecordRedirect` -```html - - - -``` +___ -## createRouter +### UseLinkOptions -Creates a Router instance that can be used by a Vue app. Check the [`RouterOptions`](#routeroptions) for a list of all the properties that can be passed. +Ƭ **UseLinkOptions**: `VueUseOptions`<`RouterLinkOptions`\> -**Signature:** +## Variables -```typescript -export declare function createRouter(options: RouterOptions): Router -``` +### RouterLink -### Parameters +• `Const` **RouterLink**: `_RouterLinkI` -| Parameter | Type | Description | -| --------- | ------------------------------- | -------------------------------- | -| options | [RouterOptions](#routeroptions) | Options to initialize the router | +Component to render a link that triggers a navigation on click. -## createWebHistory +___ -Creates an HTML5 history. Most common history for single page applications. The application must be served through the http protocol. +### RouterView -**Signature:** +• `Const` **RouterView**: () => { `$props`: `AllowedComponentProps` & `ComponentCustomProps` & `VNodeProps` & [`RouterViewProps`](interfaces/RouterViewProps.md) ; `$slots`: { `default`: (`arg`: { `Component`: `VNode`<`RendererNode`, `RendererElement`, { `[key: string]`: `any`; }\> ; `route`: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) }) => `VNode`<`RendererNode`, `RendererElement`, { `[key: string]`: `any`; }\>[] } } -```typescript -export declare function createWebHistory(base?: string): RouterHistory -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | -------- | --------------------------------------------------------------------------------------------------------------------- | -| base | `string` | optional base to provide. Useful when the application is hosted inside of a folder like `https://example.com/folder/` | - -### Examples - -```js -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/` -``` +#### Type declaration -## createWebHashHistory +• **new RouterView**() -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`](#createwebhistory) if SEO matters to you**. +Component to display the current route the user is at. -**Signature:** +___ -```typescript -export declare function createWebHashHistory(base?: string): RouterHistory -``` +### START\_LOCATION -### Parameters +• `Const` **START\_LOCATION**: [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) -| Parameter | Type | Description | -| --------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| base | `string` | optional base to provide. Defaults to `location.pathname + location.search`. If there is a `` 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 `` tag, its `href` value **has to match this parameter** (ignoring anything after the `#`) | +Initial route location where the router is. Can be used in navigation guards +to differentiate the initial navigation. -### Examples +**`Example`** ```js -// 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#` -``` - -## createMemoryHistory - -Creates a in-memory based history. The main purpose of this history is to handle SSR. It starts in a special location that is nowhere. If the user is not on a browser context, it's up to them to replace that location with the starter location by either calling `router.push()` or `router.replace()`. - -**Signature:** +import { START_LOCATION } from 'vue-router' -```typescript -export declare function createMemoryHistory(base?: string): RouterHistory +router.beforeEach((to, from) => { + if (from === START_LOCATION) { + // initial navigation + } +}) ``` -### Parameters - -| Parameter | Type | Description | -| --------- | -------- | ----------------------------------------- | -| base | `string` | Base applied to all urls, defaults to '/' | - -### Returns - -A history object that can be passed to the router constructor +## Functions -## NavigationFailureType +### createMemoryHistory -Enumeration with all possible types for navigation failures. Can be passed to [isNavigationFailure](#isnavigationfailure) to check for specific failures. **Never use any of the numerical values**, always use the variables like `NavigationFailureType.aborted`. +▸ **createMemoryHistory**(`base?`): [`RouterHistory`](interfaces/RouterHistory.md) -**Signature:** +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` or `router.replace`. -```typescript -export declare enum NavigationFailureType -``` - -### Members - -| 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. | - -## START_LOCATION +#### Parameters -- **Type**: [`RouteLocationNormalized`](#routelocationnormalized) -- **Details**: +| Name | Type | Default value | Description | +| :------ | :------ | :------ | :------ | +| `base` | `string` | `''` | Base applied to all urls, defaults to '/' | - Initial route location where the router is. Can be used in navigation guards to differentiate the initial navigation. +#### Returns - ```js - import { START_LOCATION } from 'vue-router' +[`RouterHistory`](interfaces/RouterHistory.md) - router.beforeEach((to, from) => { - if (from === START_LOCATION) { - // initial navigation - } - }) - ``` +a history object that can be passed to the router constructor -## Composition API +___ -### onBeforeRouteLeave +### createRouter -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. +▸ **createRouter**(`options`): [`Router`](interfaces/Router.md) -**Signature:** - -```typescript -export declare function onBeforeRouteLeave(leaveGuard: NavigationGuard): void -``` +Creates a Router instance that can be used by a Vue app. #### Parameters -| Parameter | Type | Description | -| ---------- | ------------------------------------- | ----------------------- | -| leaveGuard | [`NavigationGuard`](#navigationguard) | Navigation guard to add | +| Name | Type | Description | +| :------ | :------ | :------ | +| `options` | [`RouterOptions`](interfaces/RouterOptions.md) | [RouterOptions](interfaces/RouterOptions.md) | -### onBeforeRouteUpdate +#### Returns -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. +[`Router`](interfaces/Router.md) -**Signature:** - -```typescript -export declare function onBeforeRouteUpdate(updateGuard: NavigationGuard): void -``` +___ -#### Parameters +### createWebHashHistory -| Parameter | Type | Description | -| ----------- | ------------------------------------- | ----------------------- | -| updateGuard | [`NavigationGuard`](#navigationguard) | Navigation guard to add | +▸ **createWebHashHistory**(`base?`): [`RouterHistory`](interfaces/RouterHistory.md) -### useLink +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. -Returns everything exposed by the [`v-slot` API](#router-link-s-v-slot). +**`Example`** -**Signature:** +```js +// 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/#` -```typescript -export declare function useLink(props: RouterLinkOptions): { - route: ComputedRef, - href: ComputedRef, - isActive: ComputedRef, - isExactActive: ComputedRef, - navigate: (event?: MouseEvent) => Promise(NavigationFailure | void), -} +// 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#` ``` #### Parameters -| Parameter | Type | Description | -| --------- | ------------------- | ------------------------------------------------------------------------------------- | -| props | `RouterLinkOptions` | props object that can be passed to ``. Accepts `Ref`s and `ComputedRef`s | - -### useRoute - -Returns the current route location. Equivalent to using `$route` inside templates. Must be called inside of `setup()`. - -**Signature:** - -```typescript -export declare function useRoute(): RouteLocationNormalized -``` - -### useRouter - -Returns the [router](#router-properties) instance. Equivalent to using `$router` inside templates. Must be called inside of `setup()`. - -**Signature:** - -```typescript -export declare function useRouter(): Router -``` - -## TypeScript - -Here are some of the interfaces and types used by Vue Router. The documentation references them to give you an idea of the existing properties in objects. - -## Router Properties - -### currentRoute - -- **Type**: [`Ref`](#routelocationnormalized) -- **Details**: - - Current route location. Readonly. - -### options +| Name | Type | Description | +| :------ | :------ | :------ | +| `base?` | `string` | optional base to provide. Defaults to `location.pathname + location.search` If there is a `` 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 `` tag, it's `href` value **has to match this parameter** (ignoring anything after the `#`). | -- **Type**: [`RouterOptions`](#routeroptions) -- **Details**: +#### Returns - Original options object passed to create the Router. Readonly. +[`RouterHistory`](interfaces/RouterHistory.md) -## Router Methods +___ -### addRoute +### createWebHistory -Add a new [Route Record](#routerecordraw) 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. +▸ **createWebHistory**(`base?`): [`RouterHistory`](interfaces/RouterHistory.md) -**Signature:** +Creates an HTML5 history. Most common history for single page applications. -```typescript -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`](#routerecordraw) | Route Record to add | - -### addRoute - -Add a new [route record](#routerecordraw) 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:** - -```typescript -addRoute(route: RouteRecordRaw): () => void -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | ----------------------------------- | ------------------- | -| route | [`RouteRecordRaw`](#routerecordraw) | Route Record to add | +#### Parameters -:::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. -::: +| Name | Type | +| :------ | :------ | +| `base?` | `string` | -### afterEach +#### Returns -Add a navigation hook that is executed after every navigation. Returns a function that removes the registered hook. +[`RouterHistory`](interfaces/RouterHistory.md) -**Signature:** +___ -```typescript -afterEach(guard: NavigationHookAfter): () => void -``` +### isNavigationFailure -_Parameters_ +▸ **isNavigationFailure**(`error`, `type?`): error is NavigationRedirectError -| Parameter | Type | Description | -| --------- | --------------------- | ---------------------- | -| guard | `NavigationHookAfter` | navigation hook to add | +Check if an object is a [NavigationFailure](interfaces/NavigationFailure.md). -#### Examples +**`Example`** ```js +import { isNavigationFailure, NavigationFailureType } from 'vue-router' + router.afterEach((to, from, failure) => { + // Any kind of navigation failure if (isNavigationFailure(failure)) { - console.log('failed navigation', failure) + // ... + } + // Only duplicated navigations + if (isNavigationFailure(failure, NavigationFailureType.duplicated)) { + // ... + } + // Aborted or canceled navigations + if (isNavigationFailure(failure, NavigationFailureType.aborted | NavigationFailureType.canceled)) { + // ... } }) ``` -### back - -Go back in history if possible by calling `history.back()`. Equivalent to `router.go(-1)`. - -**Signature:** - -```typescript -back(): void -``` - -### beforeEach - -Add a navigation guard that executes before any navigation. Returns a function that removes the registered guard. - -**Signature:** - -```typescript -beforeEach(guard: NavigationGuard): () => void -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | ------------------------------------- | ----------------------- | -| guard | [`NavigationGuard`](#navigationguard) | navigation guard to add | - -### beforeResolve - -Add a navigation guard that executes before navigation is about to be resolved. At this state all component have been fetched and other navigation guards have been successful. Returns a function that removes the registered guard. - -**Signature:** - -```typescript -beforeResolve(guard: NavigationGuard): () => void -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | ------------------------------------- | ----------------------- | -| guard | [`NavigationGuard`](#navigationguard) | navigation guard to add | - -#### Examples - -```js -router.beforeResolve(to => { - if (to.meta.requiresAuth && !isAuthenticated) return false -}) -``` - -### forward - -Go forward in history if possible by calling `history.forward()`. Equivalent to `router.go(1)`. - -**Signature:** - -```typescript -forward(): void -``` - -### getRoutes - -Get a full list of all the [route records](#routerecordnormalized). - -**Signature:** - -```typescript -getRoutes(): RouteRecordNormalized[] -``` - -### go - -Allows you to move forward or backward through the history. - -**Signature:** - -```typescript -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 | - -### hasRoute - -Checks if a route with a given name exists - -**Signature:** - -```typescript -hasRoute(name: string | symbol): boolean -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | ------------------ | -------------------------- | -| name | `string \| symbol` | Name of the route to check | - -### isReady - -Returns a Promise that resolves when the router has completed the initial navigation, which means it has resolved all async enter hooks and async components that are associated with the initial route. If the initial navigation already happened, the promise resolves immediately.This is useful in server-side rendering to ensure consistent output on both the server and the client. Note that on server side, you need to manually push the initial location while on client side, the router automatically picks it up from the URL. - -**Signature:** - -```typescript -isReady(): Promise -``` - -### onError - -Adds an error handler that is called every time a non caught error happens during navigation. This includes errors thrown synchronously and asynchronously, errors returned or passed to `next` in any navigation guard, and errors occurred when trying to resolve an async component that is required to render a route. - -**Signature:** - -```typescript -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 | - -### push - -Programmatically navigate to a new URL by pushing an entry in the history stack. - -**Signature:** - -```typescript -push(to: RouteLocationRaw): Promise -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | --------------------------------------- | ----------------------------- | -| to | [`RouteLocationRaw`](#routelocationraw) | Route location to navigate to | - -### removeRoute - -Remove an existing route by its name. - -**Signature:** - -```typescript -removeRoute(name: string | symbol): void -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | ------------------ | --------------------------- | -| name | `string \| symbol` | Name of the route to remove | - -### replace - -Programmatically navigate to a new URL by replacing the current entry in the history stack. - -**Signature:** - -```typescript -replace(to: RouteLocationRaw): Promise -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | --------------------------------------- | ----------------------------- | -| to | [`RouteLocationRaw`](#routelocationraw) | Route location to navigate to | - -### resolve - -Returns the [normalized version](#routelocation) of a [route location](#routelocationraw). Also includes an `href` property that includes any existing `base`. - -**Signature:** - -```typescript -resolve(to: RouteLocationRaw): RouteLocation & { - href: string -} -``` - -_Parameters_ - -| Parameter | Type | Description | -| --------- | --------------------------------------- | ----------------------------- | -| to | [`RouteLocationRaw`](#routelocationraw) | Raw route location to resolve | - -## RouterOptions - -### history - -History implementation used by the router. Most web applications should use `createWebHistory` but it requires the server to be properly configured. You can also use a _hash_ based history with `createWebHashHistory` that does not require any configuration on the server but isn't handled at all by search engines and does poorly on SEO. - -**Signature:** - -```typescript -history: RouterHistory -``` - -#### Examples - -```js -createRouter({ - history: createWebHistory(), - // other options... -}) -``` - -### linkActiveClass - -Default class applied to active [RouterLink](#router-link-props). If none is provided, `router-link-active` will be applied. - -**Signature:** - -```typescript -linkActiveClass?: string -``` - -### linkExactActiveClass - -Default class applied to exact active [RouterLink](#router-link-props). If none is provided, `router-link-exact-active` will be applied. - -**Signature:** - -```typescript -linkExactActiveClass?: string -``` - -### parseQuery - -Custom implementation to parse a query. Must decode query keys and values. See its counterpart, [stringifyQuery](#stringifyquery). - -**Signature:** - -```typescript -parseQuery?: (searchQuery: string) => Record -``` - -#### Examples - -Let's say you want to use the package [qs](https://github.com/ljharb/qs) to parse queries, you can provide both `parseQuery` and `stringifyQuery`: - -```js -import qs from 'qs' - -createRouter({ - // other options... - parseQuery: qs.parse, - stringifyQuery: qs.stringify, -}) -``` - -### routes - -Initial list of routes that should be added to the router. - -**Signature:** - -```typescript -routes: RouteRecordRaw[] -``` - -### scrollBehavior - -Function to control scrolling when navigating between pages. Can return a Promise to delay when the scrolling happens. See [Scroll Behaviour](../guide/advanced/scroll-behavior.md) for more details. - -**Signature:** - -```typescript -scrollBehavior?: RouterScrollBehavior -``` - -#### Examples - -```js -function scrollBehavior(to, from, savedPosition) { - // `to` and `from` are both route locations - // `savedPosition` can be null if there isn't one -} -``` - -### stringifyQuery - -Custom implementation to stringify a query object. Should not prepend a leading `?`. Should properly encode query keys and values. [parseQuery](#parsequery) counterpart to handle query parsing. - -**Signature:** - -```typescript -stringifyQuery?: ( - query: Record< - string | number, - string | number | null | undefined | (string | number | null | undefined)[] - > -) => string -``` - -## RouteRecordRaw - -Route record that can be provided by the user when adding routes via the [`routes` option](#routeroptions) or via [`router.addRoute()`](#addroute). There are three different kind of route records: - -- Single views records: have a `component` option -- Multiple views records ([named views](../guide/essentials/named-views.md)): have a `components` option -- Redirect records: cannot have `component` or `components` option because a redirect record is never reached. - -### path - -- **Type**: `string` -- **Details**: - - Path of the record. Should start with `/` unless the record is the child of another record. Can define parameters: `/users/:id` matches `/users/1` as well as `/users/posva`. - -- **See Also**: [Dynamic Route Matching](../guide/essentials/dynamic-matching.md) - -### redirect - -- **Type**: `RouteLocationRaw | (to: RouteLocationNormalized) => RouteLocationRaw` (Optional) -- **Details**: - - Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new target location. Can also be a function that receives the target route location and returns the location we should redirect to. - -### children - -- **Type**: Array of [`RouteRecordRaw`](#routerecordraw) (Optional) -- **Details**: - - Nested routes of the current record. - -- **See Also**: [Nested Routes](../guide/essentials/nested-routes.md) - -### alias - -- **Type**: `string | string[]` (Optional) -- **Details**: - - Aliases for the route. Allows defining extra paths that will behave like a copy of the record. This enables paths shorthands like `/users/:id` and `/u/:id`. **All `alias` and `path` values must share the same params**. - -### name - -- **Type**: `string | symbol` (Optional) -- **Details**: - - Unique name for the route record. - -### beforeEnter - -- **Type**: [`NavigationGuard | NavigationGuard[]`](#navigationguard) (Optional) -- **Details**: - - Before enter guard specific to this record. Note `beforeEnter` has no effect if the record has a `redirect` property. - -### props - -- **Type**: `boolean | Record | (to: RouteLocationNormalized) => Record` (Optional) -- **Details**: - - Allows passing down params as props to the component rendered by `router-view`. When passed to a _multiple views record_, it should be an object with the same keys as `components` or a `boolean` to be applied to each component.target location. - -- **See Also**: [Passing props to Route Components](../guide/essentials/passing-props.md) - -### sensitive - -- **Type**: `boolean` (Optional) -- **Details**: - - Makes the route matching case sensitive, defaults to `false`. Note this can also be set at a route level. - -### strict - -- **Type**: `boolean` (Optional) -- **Details**: - - Strictly checks the presence or absence of a trailing slash (`/`) at the end of the path. Defaults to `false` meaning that by default a route `/users` matches both `/users` and `/users/`. Note this can also be set at a route level. - -### meta - -- **Type**: [`RouteMeta`](#routemeta) (Optional) -- **Details**: - - Custom data attached to the record. - -- **See Also**: [Meta fields](../guide/advanced/meta.md) - -:::tip -If you want to use a functional component, make sure to add a `displayName` to it. - -For example: - -```js -const HomeView = () => h('div', 'HomePage') -// in TypeScript, you will need to use the FunctionalComponent type -HomeView.displayName = 'HomeView' -const routes = [{ path: '/', component: HomeView }] -``` - -::: - -## RouteRecordNormalized - -Normalized version of a [Route Record](#routerecordraw) - -### aliasOf - -- **Type**: `RouteRecordNormalized | undefined` -- **Details**: - - Defines if this record is the alias of another one. This property is `undefined` if the record is the original one. - -### beforeEnter - -- **Type**: [`NavigationGuard`](#navigationguard) -- **Details**: - - Navigation guard applied when entering this record from somewhere else. - -- **See Also**: [Navigation guards](../guide/advanced/navigation-guards.md) - -### children - -- **Type**: Array of normalized [route records](#routerecordnormalized) -- **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()` and `removeRoute()` are called. - -### components - -- **Type**: `Record` -- **Details**: - - Dictionary of named views, if none, contains an object with the key `default`. - -### meta - -- **Type**: `RouteMeta` -- **Details**: - - Arbitrary data attached to the record. - -- **See also**: [Meta fields](../guide/advanced/meta.md) - -### name - -- **Type**: `string | symbol | undefined` -- **Details**: - - Name for the route record. `undefined` if none was provided. - -### path - -- **Type**: `string` -- **Details**: - - Normalized path of the record. Includes any parent's `path`. - -### props - -- **Type**: `Record>` -- **Details**: - - Dictionary of the [`props` option](#props) for each named view. If none, it will contain only one property named `default`. - -### redirect - -- **Type**: [`RouteLocationRaw`](#routelocationraw) -- **Details**: - - Where to redirect if the route is directly matched. The redirection happens before any navigation guard and triggers a new navigation with the new target location. - -## RouteLocationRaw - -User-level route location that can be passed to `router.push()`, `redirect`, and returned in [Navigation Guards](../guide/advanced/navigation-guards.md). - -A raw location can either be a `string` like `/users/posva#bio` or an object: - -```js -// 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()`: - -```js -router.push({ hash: '#bio', replace: true }) -// equivalent to -router.replace({ hash: '#bio' }) -``` - -## RouteLocation - -Resolved [RouteLocationRaw](#routelocationraw) that can contain [redirect records](#routerecordraw). Apart from that it has the same properties as [RouteLocationNormalized](#routelocationnormalized). - -## RouteLocationNormalized - -Normalized route location. Does not have any [redirect records](#routerecordraw). In navigation guards, `to` and `from` are always of this type. - -### fullPath - -- **Type**: `string` -- **Details**: - - Encoded URL associated to the route location. Contains `path`, `query` and `hash`. - -### hash +#### Parameters -- **Type**: `string` -- **Details**: +| Name | Type | Description | +| :------ | :------ | :------ | +| `error` | `any` | possible [NavigationFailure](interfaces/NavigationFailure.md) | +| `type?` | `NAVIGATION_GUARD_REDIRECT` | optional types to check for | - Decoded `hash` section of the URL. Always starts with a `#`. Empty string if there is no `hash` in the URL. +#### Returns -### query +error is NavigationRedirectError -- **Type**: `Record` -- **Details**: +▸ **isNavigationFailure**(`error`, `type?`): error is NavigationFailure - Dictionary of decoded query params extracted from the `search` section of the URL. +#### Parameters -### matched +| Name | Type | +| :------ | :------ | +| `error` | `any` | +| `type?` | `ErrorTypes` \| [`NavigationFailureType`](enums/NavigationFailureType.md) | -- **Type**: [`RouteRecordNormalized[]`](#routerecordnormalized) -- **Details**: +#### Returns - Array of [normalized route records](#routerecordnormalized) that were matched with the given route location. +error is NavigationFailure -### meta +___ -- **Type**: `RouteMeta` -- **Details**: +### loadRouteLocation - Arbitrary data attached to all matched records merged (non recursively) from parent to child. +▸ **loadRouteLocation**(`route`): `Promise`<[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md)\> -- **See also**: [Meta fields](../guide/advanced/meta.md) +Ensures a route is loaded, so it can be passed as o prop to ``. -### name +#### Parameters -- **Type**: `string | symbol | undefined | null` -- **Details**: +| Name | Type | Description | +| :------ | :------ | :------ | +| `route` | [`RouteLocationNormalized`](interfaces/RouteLocationNormalized.md) | resolved route to load | - Name for the route record. `undefined` if none was provided. +#### Returns -### params +`Promise`<[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md)\> -- **Type**: `Record` -- **Details**: +___ - Dictionary of decoded params extracted from `path`. +### onBeforeRouteLeave -### path +▸ **onBeforeRouteLeave**(`leaveGuard`): `void` -- **Type**: `string` -- **Details**: +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. - Encoded `pathname` section of the URL associated to the route location. +#### Parameters -### redirectedFrom +| Name | Type | Description | +| :------ | :------ | :------ | +| `leaveGuard` | [`NavigationGuard`](interfaces/NavigationGuard.md) | [NavigationGuard](interfaces/NavigationGuard.md) | -- **Type**: [`RouteLocation`](#routelocation) -- **Details**: +#### Returns - Route location we were initially trying to access before ending up on the current location when a `redirect` option was found or a navigation guard called `next()` with a route location. `undefined` if there was no redirection. +`void` -## NavigationFailure +___ -### from +### onBeforeRouteUpdate -- **Type**: [`RouteLocationNormalized`](#routelocationnormalized) -- **Details**: +▸ **onBeforeRouteUpdate**(`updateGuard`): `void` - Route location we were navigating from +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. -### to +#### Parameters -- **Type**: [`RouteLocationNormalized`](#routelocationnormalized) -- **Details**: +| Name | Type | Description | +| :------ | :------ | :------ | +| `updateGuard` | [`NavigationGuard`](interfaces/NavigationGuard.md) | [NavigationGuard](interfaces/NavigationGuard.md) | - Route location we were navigating to +#### Returns -### type +`void` -- **Type**: [`NavigationFailureType`](#navigationfailuretype) -- **Details**: +___ - Type of the navigation failure. +### useLink -- **See Also**: [Navigation Failures](../guide/advanced/navigation-failures.md) +▸ **useLink**(`props`): `Object` -## NavigationGuard +#### Parameters -- **Arguments**: +| Name | Type | +| :------ | :------ | +| `props` | `VueUseOptions`<`RouterLinkOptions`\> | - - [`RouteLocationNormalized`](#routelocationnormalized) to - Route location we are navigating to - - [`RouteLocationNormalized`](#routelocationnormalized) from - Route location we are navigating from - - `Function` next (Optional) - Callback to validate the navigation +#### Returns -- **Details**: +`Object` - Function that can be passed to control a router navigation. The `next` callback can be omitted if you return a value (or a Promise) instead, which is encouraged. Possible return values (and parameters for `next`) are: +| Name | Type | +| :------ | :------ | +| `href` | `ComputedRef`<`string`\> | +| `isActive` | `ComputedRef`<`boolean`\> | +| `isExactActive` | `ComputedRef`<`boolean`\> | +| `navigate` | (`e`: `MouseEvent`) => `Promise`<`void` \| [`NavigationFailure`](interfaces/NavigationFailure.md)\> | +| `route` | `ComputedRef`<[`RouteLocation`](interfaces/RouteLocation.md) & { `href`: `string` }\> | - - `undefined | void | true`: validates the navigation - - `false`: cancels the navigation - - [`RouteLocationRaw`](#routelocationraw): redirects to a different location - - `(vm: ComponentPublicInstance) => any` **only for `beforeRouteEnter`**: A callback to be executed once the navigation completes. Receives the route component instance as the parameter. +___ -- **See Also**: [Navigation Guards](../guide/advanced/navigation-guards.md) +### useRoute -## Component Injections +▸ **useRoute**(): [`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) -### Component Injected Properties +Returns the current route location. Equivalent to using `$route` inside +templates. -These properties are injected into every child component by calling `app.use(router)`. +#### Returns -- **this.\$router** +[`RouteLocationNormalizedLoaded`](interfaces/RouteLocationNormalizedLoaded.md) - The router instance. +___ -- **this.\$route** +### useRouter - The current active [route location](#routelocationnormalized). This property is read-only and its properties are immutable, but it can be watched. +▸ **useRouter**(): [`Router`](interfaces/Router.md) -### Component Enabled Options +Returns the router instance. Equivalent to using `$router` inside +templates. -- **beforeRouteEnter** -- **beforeRouteUpdate** -- **beforeRouteLeave** +#### Returns -See [In Component Guards](../guide/advanced/navigation-guards.md#in-component-guards). +[`Router`](interfaces/Router.md) diff --git a/packages/docs/api/interfaces/HistoryState.md b/packages/docs/api/interfaces/HistoryState.md new file mode 100644 index 00000000..df9de68c --- /dev/null +++ b/packages/docs/api/interfaces/HistoryState.md @@ -0,0 +1,15 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / HistoryState + +# Interface: HistoryState + +Allowed HTML history.state + +## Indexable + +▪ [x: `number`]: `HistoryStateValue` diff --git a/packages/docs/api/interfaces/NavigationFailure.md b/packages/docs/api/interfaces/NavigationFailure.md new file mode 100644 index 00000000..998d030b --- /dev/null +++ b/packages/docs/api/interfaces/NavigationFailure.md @@ -0,0 +1,81 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationFailure + +# Interface: NavigationFailure + +Extended Error that contains extra information regarding a failed navigation. + +## Hierarchy + +- `Error` + + ↳ **`NavigationFailure`** + +## Properties + +### cause + +• `Optional` **cause**: `Error` + +#### Inherited from + +Error.cause + +___ + +### from + +• **from**: [`RouteLocationNormalized`](RouteLocationNormalized.md) + +Route location we were navigating from + +___ + +### message + +• **message**: `string` + +#### Inherited from + +Error.message + +___ + +### name + +• **name**: `string` + +#### Inherited from + +Error.name + +___ + +### stack + +• `Optional` **stack**: `string` + +#### Inherited from + +Error.stack + +___ + +### to + +• **to**: [`RouteLocationNormalized`](RouteLocationNormalized.md) + +Route location we were navigating to + +___ + +### type + +• **type**: `NAVIGATION_ABORTED` \| `NAVIGATION_CANCELLED` \| `NAVIGATION_DUPLICATED` + +Type of the navigation. One of [NavigationFailureType](../enums/NavigationFailureType.md) diff --git a/packages/docs/api/interfaces/NavigationGuard.md b/packages/docs/api/interfaces/NavigationGuard.md new file mode 100644 index 00000000..996ef237 --- /dev/null +++ b/packages/docs/api/interfaces/NavigationGuard.md @@ -0,0 +1,30 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationGuard + +# Interface: NavigationGuard + +## Callable + +### NavigationGuard + +▸ **NavigationGuard**(`to`, `from`, `next`): `NavigationGuardReturn` \| `Promise`<`NavigationGuardReturn`\> + +Navigation guard. See [Navigation +Guards](/guide/advanced/navigation-guards.md). + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `next` | [`NavigationGuardNext`](NavigationGuardNext.md) | + +#### Returns + +`NavigationGuardReturn` \| `Promise`<`NavigationGuardReturn`\> diff --git a/packages/docs/api/interfaces/NavigationGuardNext.md b/packages/docs/api/interfaces/NavigationGuardNext.md new file mode 100644 index 00000000..af287c55 --- /dev/null +++ b/packages/docs/api/interfaces/NavigationGuardNext.md @@ -0,0 +1,75 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationGuardNext + +# Interface: NavigationGuardNext + +## Callable + +### NavigationGuardNext + +▸ **NavigationGuardNext**(): `void` + +#### Returns + +`void` + +### NavigationGuardNext + +▸ **NavigationGuardNext**(`error`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `error` | `Error` | + +#### Returns + +`void` + +### NavigationGuardNext + +▸ **NavigationGuardNext**(`location`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `location` | [`RouteLocationRaw`](../index.md#routelocationraw) | + +#### Returns + +`void` + +### NavigationGuardNext + +▸ **NavigationGuardNext**(`valid`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `valid` | `undefined` \| `boolean` | + +#### Returns + +`void` + +### NavigationGuardNext + +▸ **NavigationGuardNext**(`cb`): `void` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `cb` | `NavigationGuardNextCallback` | + +#### Returns + +`void` diff --git a/packages/docs/api/interfaces/NavigationGuardWithThis.md b/packages/docs/api/interfaces/NavigationGuardWithThis.md new file mode 100644 index 00000000..155b9e1b --- /dev/null +++ b/packages/docs/api/interfaces/NavigationGuardWithThis.md @@ -0,0 +1,37 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationGuardWithThis + +# Interface: NavigationGuardWithThis + +## Type parameters + +| Name | +| :------ | +| `T` | + +## Callable + +### NavigationGuardWithThis + +▸ **NavigationGuardWithThis**(`this`, `to`, `from`, `next`): `NavigationGuardReturn` \| `Promise`<`NavigationGuardReturn`\> + +Navigation guard. See [Navigation +Guards](/guide/advanced/navigation-guards.md). + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `this` | `T` | +| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `next` | [`NavigationGuardNext`](NavigationGuardNext.md) | + +#### Returns + +`NavigationGuardReturn` \| `Promise`<`NavigationGuardReturn`\> diff --git a/packages/docs/api/interfaces/NavigationHookAfter.md b/packages/docs/api/interfaces/NavigationHookAfter.md new file mode 100644 index 00000000..6724e455 --- /dev/null +++ b/packages/docs/api/interfaces/NavigationHookAfter.md @@ -0,0 +1,27 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / NavigationHookAfter + +# Interface: NavigationHookAfter + +## Callable + +### NavigationHookAfter + +▸ **NavigationHookAfter**(`to`, `from`, `failure?`): `any` + +#### Parameters + +| Name | Type | +| :------ | :------ | +| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `from` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | +| `failure?` | `void` \| [`NavigationFailure`](NavigationFailure.md) | + +#### Returns + +`any` diff --git a/packages/docs/api/interfaces/RouteLocation.md b/packages/docs/api/interfaces/RouteLocation.md new file mode 100644 index 00000000..49b8038b --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocation.md @@ -0,0 +1,125 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteLocation + +# Interface: RouteLocation + +[RouteLocationRaw](../index.md#routelocationraw) resolved using the matcher + +## Hierarchy + +- `_RouteLocationBase` + + ↳ **`RouteLocation`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +\_RouteLocationBase.fullPath + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +\_RouteLocationBase.hash + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecord](../index.md#routerecord) containing components as they were +passed when adding records. It can also contain redirect records. This +can't be used directly + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +\_RouteLocationBase.meta + +___ + +### name + +• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#routerecordname) + +Name of the matched record + +#### Inherited from + +\_RouteLocationBase.name + +___ + +### params + +• **params**: [`RouteParams`](../index.md#routeparams) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +\_RouteLocationBase.params + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +\_RouteLocationBase.path + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#locationquery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +\_RouteLocationBase.query + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationMatched.md b/packages/docs/api/interfaces/RouteLocationMatched.md new file mode 100644 index 00000000..9f7bf7da --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationMatched.md @@ -0,0 +1,144 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteLocationMatched + +# Interface: RouteLocationMatched + +Normalized version of a [route record](../index.md#routerecord). + +## Hierarchy + +- [`RouteRecordNormalized`](RouteRecordNormalized.md) + + ↳ **`RouteLocationMatched`** + +## Properties + +### aliasOf + +• **aliasOf**: `undefined` \| [`RouteRecordNormalized`](RouteRecordNormalized.md) + +Defines if this record is the alias of another one. This property is +`undefined` if the record is the original one. + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[aliasOf](RouteRecordNormalized.md#aliasof) + +___ + +### beforeEnter + +• **beforeEnter**: `undefined` \| [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\> \| [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\>[] + +Registered beforeEnter guards + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[beforeEnter](RouteRecordNormalized.md#beforeenter) + +___ + +### children + +• **children**: [`RouteRecordRaw`](../index.md#routerecordraw)[] + +Nested route records. + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[children](RouteRecordNormalized.md#children) + +___ + +### components + +• **components**: `undefined` \| ``null`` \| `Record`<`string`, [`RouteComponent`](../index.md#routecomponent)\> + +{@inheritDoc RouteRecordMultipleViews.components} + +#### Overrides + +[RouteRecordNormalized](RouteRecordNormalized.md).[components](RouteRecordNormalized.md#components) + +___ + +### instances + +• **instances**: `Record`<`string`, `undefined` \| ``null`` \| `ComponentPublicInstance`<{}, {}, {}, {}, {}, {}, {}, {}, ``false``, `ComponentOptionsBase`<`any`, `any`, `any`, `any`, `any`, `any`, `any`, `any`, `any`, {}\>\>\> + +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. + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[instances](RouteRecordNormalized.md#instances) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +{@inheritDoc _RouteRecordBase.meta} + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[meta](RouteRecordNormalized.md#meta) + +___ + +### name + +• **name**: `undefined` \| [`RouteRecordName`](../index.md#routerecordname) + +{@inheritDoc _RouteRecordBase.name} + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[name](RouteRecordNormalized.md#name) + +___ + +### path + +• **path**: `string` + +{@inheritDoc _RouteRecordBase.path} + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[path](RouteRecordNormalized.md#path) + +___ + +### props + +• **props**: `Record`<`string`, `_RouteRecordProps`\> + +{@inheritDoc RouteRecordMultipleViews.props} + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[props](RouteRecordNormalized.md#props) + +___ + +### redirect + +• **redirect**: `undefined` \| `RouteRecordRedirectOption` + +{@inheritDoc _RouteRecordBase.redirect} + +#### Inherited from + +[RouteRecordNormalized](RouteRecordNormalized.md).[redirect](RouteRecordNormalized.md#redirect) diff --git a/packages/docs/api/interfaces/RouteLocationNormalized.md b/packages/docs/api/interfaces/RouteLocationNormalized.md new file mode 100644 index 00000000..f670c6eb --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalized.md @@ -0,0 +1,124 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteLocationNormalized + +# Interface: RouteLocationNormalized + +Similar to [RouteLocation](RouteLocation.md) but its +[matched](RouteLocationNormalized.md#matched) cannot contain redirect records + +## Hierarchy + +- `_RouteLocationBase` + + ↳ **`RouteLocationNormalized`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +\_RouteLocationBase.fullPath + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +\_RouteLocationBase.hash + +___ + +### matched + +• **matched**: [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Array of [RouteRecordNormalized](RouteRecordNormalized.md) + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +\_RouteLocationBase.meta + +___ + +### name + +• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#routerecordname) + +Name of the matched record + +#### Inherited from + +\_RouteLocationBase.name + +___ + +### params + +• **params**: [`RouteParams`](../index.md#routeparams) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +\_RouteLocationBase.params + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +\_RouteLocationBase.path + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#locationquery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +\_RouteLocationBase.query + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md b/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md new file mode 100644 index 00000000..c354a10c --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationNormalizedLoaded.md @@ -0,0 +1,126 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteLocationNormalizedLoaded + +# Interface: RouteLocationNormalizedLoaded + +[RouteLocationRaw](../index.md#routelocationraw) with + +## Hierarchy + +- `_RouteLocationBase` + + ↳ **`RouteLocationNormalizedLoaded`** + +## Properties + +### fullPath + +• **fullPath**: `string` + +The whole location including the `search` and `hash`. This string is +percentage encoded. + +#### Inherited from + +\_RouteLocationBase.fullPath + +___ + +### hash + +• **hash**: `string` + +Hash of the current location. If present, starts with a `#`. + +#### Inherited from + +\_RouteLocationBase.hash + +___ + +### matched + +• **matched**: [`RouteLocationMatched`](RouteLocationMatched.md)[] + +Array of [RouteLocationMatched](RouteLocationMatched.md) 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 + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +Merged `meta` properties from all the matched route records. + +#### Inherited from + +\_RouteLocationBase.meta + +___ + +### name + +• **name**: `undefined` \| ``null`` \| [`RouteRecordName`](../index.md#routerecordname) + +Name of the matched record + +#### Inherited from + +\_RouteLocationBase.name + +___ + +### params + +• **params**: [`RouteParams`](../index.md#routeparams) + +Object of decoded params extracted from the `path`. + +#### Inherited from + +\_RouteLocationBase.params + +___ + +### path + +• **path**: `string` + +Percentage encoded pathname section of the URL. + +#### Inherited from + +\_RouteLocationBase.path + +___ + +### query + +• **query**: [`LocationQuery`](../index.md#locationquery) + +Object representation of the `search` property of the current location. + +#### Inherited from + +\_RouteLocationBase.query + +___ + +### redirectedFrom + +• **redirectedFrom**: `undefined` \| [`RouteLocation`](RouteLocation.md) + +Contains the location we were initially trying to access before ending up +on the current location. + +#### Inherited from + +\_RouteLocationBase.redirectedFrom diff --git a/packages/docs/api/interfaces/RouteLocationOptions.md b/packages/docs/api/interfaces/RouteLocationOptions.md new file mode 100644 index 00000000..fb8afd54 --- /dev/null +++ b/packages/docs/api/interfaces/RouteLocationOptions.md @@ -0,0 +1,39 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteLocationOptions + +# Interface: RouteLocationOptions + +Common options for all navigation methods. + +## Properties + +### force + +• `Optional` **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. + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Replace the entry in the history instead of pushing a new entry + +___ + +### state + +• `Optional` **state**: [`HistoryState`](HistoryState.md) + +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 diff --git a/packages/docs/api/interfaces/RouteMeta.md b/packages/docs/api/interfaces/RouteMeta.md new file mode 100644 index 00000000..0b80a900 --- /dev/null +++ b/packages/docs/api/interfaces/RouteMeta.md @@ -0,0 +1,30 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteMeta + +# Interface: RouteMeta + +Interface to type `meta` fields in route records. + +**`Example`** + +```ts +// typings.d.ts or router.ts +import 'vue-router'; + +declare module 'vue-router' { + interface RouteMeta { + requiresAuth?: boolean + } + } +``` + +## Hierarchy + +- `Record`<`string` \| `number` \| `symbol`, `unknown`\> + + ↳ **`RouteMeta`** diff --git a/packages/docs/api/interfaces/RouteRecordNormalized.md b/packages/docs/api/interfaces/RouteRecordNormalized.md new file mode 100644 index 00000000..ef5ad417 --- /dev/null +++ b/packages/docs/api/interfaces/RouteRecordNormalized.md @@ -0,0 +1,104 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouteRecordNormalized + +# Interface: RouteRecordNormalized + +Normalized version of a [route record](../index.md#routerecord). + +## Hierarchy + +- **`RouteRecordNormalized`** + + ↳ [`RouteLocationMatched`](RouteLocationMatched.md) + +## Properties + +### aliasOf + +• **aliasOf**: `undefined` \| [`RouteRecordNormalized`](RouteRecordNormalized.md) + +Defines if this record is the alias of another one. This property is +`undefined` if the record is the original one. + +___ + +### beforeEnter + +• **beforeEnter**: `undefined` \| [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\> \| [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\>[] + +Registered beforeEnter guards + +___ + +### children + +• **children**: [`RouteRecordRaw`](../index.md#routerecordraw)[] + +Nested route records. + +___ + +### components + +• **components**: `undefined` \| ``null`` \| `Record`<`string`, `RawRouteComponent`\> + +{@inheritDoc RouteRecordMultipleViews.components} + +___ + +### instances + +• **instances**: `Record`<`string`, `undefined` \| ``null`` \| `ComponentPublicInstance`<{}, {}, {}, {}, {}, {}, {}, {}, ``false``, `ComponentOptionsBase`<`any`, `any`, `any`, `any`, `any`, `any`, `any`, `any`, `any`, {}\>\>\> + +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. + +___ + +### meta + +• **meta**: [`RouteMeta`](RouteMeta.md) + +{@inheritDoc _RouteRecordBase.meta} + +___ + +### name + +• **name**: `undefined` \| [`RouteRecordName`](../index.md#routerecordname) + +{@inheritDoc _RouteRecordBase.name} + +___ + +### path + +• **path**: `string` + +{@inheritDoc _RouteRecordBase.path} + +___ + +### props + +• **props**: `Record`<`string`, `_RouteRecordProps`\> + +{@inheritDoc RouteRecordMultipleViews.props} + +___ + +### redirect + +• **redirect**: `undefined` \| `RouteRecordRedirectOption` + +{@inheritDoc _RouteRecordBase.redirect} diff --git a/packages/docs/api/interfaces/Router.md b/packages/docs/api/interfaces/Router.md new file mode 100644 index 00000000..f582dd3c --- /dev/null +++ b/packages/docs/api/interfaces/Router.md @@ -0,0 +1,415 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / Router + +# Interface: Router + +Router instance. + +## Properties + +### currentRoute + +• `Readonly` **currentRoute**: `Ref`<[`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md)\> + +Current [RouteLocationNormalized](RouteLocationNormalized.md) + +___ + +### listening + +• **listening**: `boolean` + +Allows turning off the listening of history events. This is a low level api for micro-frontends. + +___ + +### options + +• `Readonly` **options**: [`RouterOptions`](RouterOptions.md) + +Original options object passed to create the Router + +## Methods + +### addRoute + +▸ **addRoute**(`parentName`, `route`): () => `void` + +Add a new [route record](../index.md#routerecordraw) as the child of an existing route. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `parentName` | [`RouteRecordName`](../index.md#routerecordname) | Parent Route Record where `route` should be appended at | +| `route` | [`RouteRecordRaw`](../index.md#routerecordraw) | Route Record to add | + +#### Returns + +`fn` + +▸ (): `void` + +Add a new [route record](../index.md#routerecordraw) as the child of an existing route. + +##### Returns + +`void` + +▸ **addRoute**(`route`): () => `void` + +Add a new [route record](../index.md#routerecordraw) to the router. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `route` | [`RouteRecordRaw`](../index.md#routerecordraw) | Route Record to add | + +#### Returns + +`fn` + +▸ (): `void` + +Add a new [route record](../index.md#routerecordraw) to the router. + +##### Returns + +`void` + +___ + +### afterEach + +▸ **afterEach**(`guard`): () => `void` + +Add a navigation hook that is executed after every navigation. Returns a +function that removes the registered hook. + +**`Example`** + +```js +router.afterEach((to, from, failure) => { + if (isNavigationFailure(failure)) { + console.log('failed navigation', failure) + } +}) +``` + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `guard` | [`NavigationHookAfter`](NavigationHookAfter.md) | navigation hook to add | + +#### Returns + +`fn` + +▸ (): `void` + +Add a navigation hook that is executed after every navigation. Returns a +function that removes the registered hook. + +**`Example`** + +```js +router.afterEach((to, from, failure) => { + if (isNavigationFailure(failure)) { + console.log('failed navigation', failure) + } +}) +``` + +##### Returns + +`void` + +___ + +### back + +▸ **back**(): `void` + +Go back in history if possible by calling `history.back()`. Equivalent to +`router.go(-1)`. + +#### Returns + +`void` + +___ + +### beforeEach + +▸ **beforeEach**(`guard`): () => `void` + +Add a navigation guard that executes before any navigation. Returns a +function that removes the registered guard. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `guard` | [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\> | navigation guard to add | + +#### Returns + +`fn` + +▸ (): `void` + +Add a navigation guard that executes before any navigation. Returns a +function that removes the registered guard. + +##### Returns + +`void` + +___ + +### beforeResolve + +▸ **beforeResolve**(`guard`): () => `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. + +**`Example`** + +```js +router.beforeResolve(to => { + if (to.meta.requiresAuth && !isAuthenticated) return false +}) +``` + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `guard` | [`NavigationGuardWithThis`](NavigationGuardWithThis.md)<`undefined`\> | navigation guard to add | + +#### Returns + +`fn` + +▸ (): `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. + +**`Example`** + +```js +router.beforeResolve(to => { + if (to.meta.requiresAuth && !isAuthenticated) return false +}) +``` + +##### Returns + +`void` + +___ + +### forward + +▸ **forward**(): `void` + +Go forward in history if possible by calling `history.forward()`. +Equivalent to `router.go(1)`. + +#### Returns + +`void` + +___ + +### getRoutes + +▸ **getRoutes**(): [`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +Get a full list of all the [route records](../index.md#routerecord). + +#### Returns + +[`RouteRecordNormalized`](RouteRecordNormalized.md)[] + +___ + +### go + +▸ **go**(`delta`): `void` + +Allows you to move forward or backward through the history. Calls +`history.go()`. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `delta` | `number` | The position in the history to which you want to move, relative to the current page | + +#### Returns + +`void` + +___ + +### hasRoute + +▸ **hasRoute**(`name`): `boolean` + +Checks if a route with a given name exists + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `name` | [`RouteRecordName`](../index.md#routerecordname) | Name of the route to check | + +#### Returns + +`boolean` + +___ + +### 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. + +#### Returns + +`Promise`<`void`\> + +___ + +### onError + +▸ **onError**(`handler`): () => `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. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `handler` | `_ErrorHandler` | error handler to register | + +#### Returns + +`fn` + +▸ (): `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. + +##### Returns + +`void` + +___ + +### push + +▸ **push**(`to`): `Promise`<`undefined` \| `void` \| [`NavigationFailure`](NavigationFailure.md)\> + +Programmatically navigate to a new URL by pushing an entry in the history +stack. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | [`RouteLocationRaw`](../index.md#routelocationraw) | Route location to navigate to | + +#### Returns + +`Promise`<`undefined` \| `void` \| [`NavigationFailure`](NavigationFailure.md)\> + +___ + +### removeRoute + +▸ **removeRoute**(`name`): `void` + +Remove an existing route by its name. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `name` | [`RouteRecordName`](../index.md#routerecordname) | Name of the route to remove | + +#### Returns + +`void` + +___ + +### replace + +▸ **replace**(`to`): `Promise`<`undefined` \| `void` \| [`NavigationFailure`](NavigationFailure.md)\> + +Programmatically navigate to a new URL by replacing the current entry in +the history stack. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | [`RouteLocationRaw`](../index.md#routelocationraw) | Route location to navigate to | + +#### Returns + +`Promise`<`undefined` \| `void` \| [`NavigationFailure`](NavigationFailure.md)\> + +___ + +### resolve + +▸ **resolve**(`to`, `currentLocation?`): [`RouteLocation`](RouteLocation.md) & { `href`: `string` } + +Returns the [normalized version](RouteLocation.md) of a +[route location](../index.md#routelocationraw). Also includes an `href` property +that includes any existing `base`. By default, the `currentLocation` used is +`route.currentRoute` and should only be overridden in advanced use cases. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | [`RouteLocationRaw`](../index.md#routelocationraw) | Raw route location to resolve | +| `currentLocation?` | [`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md) | Optional current location to resolve against | + +#### Returns + +[`RouteLocation`](RouteLocation.md) & { `href`: `string` } diff --git a/packages/docs/api/interfaces/RouterHistory.md b/packages/docs/api/interfaces/RouterHistory.md new file mode 100644 index 00000000..ca2112cb --- /dev/null +++ b/packages/docs/api/interfaces/RouterHistory.md @@ -0,0 +1,170 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouterHistory + +# Interface: RouterHistory + +Interface implemented by History implementations that can be passed to the +router as Router.history + +## Properties + +### 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 a `base` of +`/sub-folder` + +___ + +### location + +• `Readonly` **location**: `string` + +Current History location + +___ + +### state + +• `Readonly` **state**: [`HistoryState`](HistoryState.md) + +Current History state + +## Methods + +### createHref + +▸ **createHref**(`location`): `string` + +Generates the corresponding href to be used in an anchor tag. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `location` | `string` | history location that should create an href | + +#### Returns + +`string` + +___ + +### destroy + +▸ **destroy**(): `void` + +Clears any event listener attached by the history implementation. + +#### Returns + +`void` + +___ + +### go + +▸ **go**(`delta`, `triggerListeners?`): `void` + +Traverses history in a given direction. + +**`Example`** + +```js +myHistory.go(-1) // equivalent to window.history.back() +myHistory.go(1) // equivalent to window.history.forward() +``` + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `delta` | `number` | distance to travel. If delta is \< 0, it will go back, if it's \> 0, it will go forward by that amount of entries. | +| `triggerListeners?` | `boolean` | whether this should trigger listeners attached to the history | + +#### Returns + +`void` + +___ + +### listen + +▸ **listen**(`callback`): () => `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.forward + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `callback` | `NavigationCallback` | listener to attach | + +#### Returns + +`fn` + +a callback to remove the listener + +▸ (): `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.forward + +##### Returns + +`void` + +a callback to remove the listener + +___ + +### push + +▸ **push**(`to`, `data?`): `void` + +Navigates to a location. In the case of an HTML5 History implementation, +this will call `history.pushState` to effectively change the URL. + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | `string` | location to push | +| `data?` | [`HistoryState`](HistoryState.md) | optional [HistoryState](HistoryState.md) to be associated with the navigation entry | + +#### Returns + +`void` + +___ + +### replace + +▸ **replace**(`to`, `data?`): `void` + +Same as [push](RouterHistory.md#push) but performs a `history.replaceState` +instead of `history.pushState` + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | `string` | location to set | +| `data?` | [`HistoryState`](HistoryState.md) | optional [HistoryState](HistoryState.md) to be associated with the navigation entry | + +#### Returns + +`void` diff --git a/packages/docs/api/interfaces/RouterLinkProps.md b/packages/docs/api/interfaces/RouterLinkProps.md new file mode 100644 index 00000000..3d7fce14 --- /dev/null +++ b/packages/docs/api/interfaces/RouterLinkProps.md @@ -0,0 +1,76 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouterLinkProps + +# Interface: RouterLinkProps + +## Hierarchy + +- `RouterLinkOptions` + + ↳ **`RouterLinkProps`** + +## Properties + +### activeClass + +• `Optional` **activeClass**: `string` + +Class to apply when the link is active + +___ + +### ariaCurrentValue + +• `Optional` **ariaCurrentValue**: ``"location"`` \| ``"time"`` \| ``"page"`` \| ``"step"`` \| ``"date"`` \| ``"true"`` \| ``"false"`` + +Value passed to the attribute `aria-current` when the link is exact active. + +**`Default Value`** + +`'page'` + +___ + +### custom + +• `Optional` **custom**: `boolean` + +Whether RouterLink should not wrap its content in an `a` tag. Useful when +using `v-slot` to create a custom RouterLink + +___ + +### exactActiveClass + +• `Optional` **exactActiveClass**: `string` + +Class to apply when the link is exact active + +___ + +### replace + +• `Optional` **replace**: `boolean` + +Calls `router.replace` instead of `router.push`. + +#### Inherited from + +RouterLinkOptions.replace + +___ + +### to + +• **to**: [`RouteLocationRaw`](../index.md#routelocationraw) + +Route Location the link should navigate to when clicked on. + +#### Inherited from + +RouterLinkOptions.to diff --git a/packages/docs/api/interfaces/RouterOptions.md b/packages/docs/api/interfaces/RouterOptions.md new file mode 100644 index 00000000..443bdc93 --- /dev/null +++ b/packages/docs/api/interfaces/RouterOptions.md @@ -0,0 +1,162 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouterOptions + +# Interface: RouterOptions + +Options to initialize a [Router](Router.md) instance. + +## Hierarchy + +- [`PathParserOptions`](../index.md#pathparseroptions) + + ↳ **`RouterOptions`** + +## Properties + +### end + +• `Optional` **end**: `boolean` + +Should the RegExp match until the end by appending a `$` to it. + +**`Default Value`** + +`true` + +#### Inherited from + +PathParserOptions.end + +___ + +### history + +• **history**: [`RouterHistory`](RouterHistory.md) + +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. + +**`Example`** + +```js +createRouter({ + history: createWebHistory(), + // other options... +}) +``` + +___ + +### linkActiveClass + +• `Optional` **linkActiveClass**: `string` + +Default class applied to active [RouterLink](../index.md#routerlink). If none is provided, +`router-link-active` will be applied. + +___ + +### linkExactActiveClass + +• `Optional` **linkExactActiveClass**: `string` + +Default class applied to exact active [RouterLink](../index.md#routerlink). If none is provided, +`router-link-exact-active` will be applied. + +___ + +### parseQuery + +• `Optional` **parseQuery**: + +Custom implementation to parse a query. See its counterpart, +[stringifyQuery](RouterOptions.md#stringifyquery). + +**`Example`** + +Let's say you want to use the [qs package](https://github.com/ljharb/qs) +to parse queries, you can provide both `parseQuery` and `stringifyQuery`: +```js +import qs from 'qs' + +createRouter({ + // other options... + parseQuery: qs.parse, + stringifyQuery: qs.stringify, +}) +``` + +___ + +### routes + +• **routes**: readonly [`RouteRecordRaw`](../index.md#routerecordraw)[] + +Initial list of routes that should be added to the router. + +___ + +### scrollBehavior + +• `Optional` **scrollBehavior**: [`RouterScrollBehavior`](RouterScrollBehavior.md) + +Function to control scrolling when navigating between pages. Can return a +Promise to delay scrolling. Check ScrollBehavior. + +**`Example`** + +```js +function scrollBehavior(to, from, savedPosition) { + // `to` and `from` are both route locations + // `savedPosition` can be null if there isn't one +} +``` + +___ + +### sensitive + +• `Optional` **sensitive**: `boolean` + +Makes the RegExp case-sensitive. + +**`Default Value`** + +`false` + +#### Inherited from + +PathParserOptions.sensitive + +___ + +### strict + +• `Optional` **strict**: `boolean` + +Whether to disallow a trailing slash or not. + +**`Default Value`** + +`false` + +#### Inherited from + +PathParserOptions.strict + +___ + +### stringifyQuery + +• `Optional` **stringifyQuery**: + +Custom implementation to stringify a query object. Should not prepend a leading `?`. +[parseQuery](RouterOptions.md#parsequery) counterpart to handle query parsing. diff --git a/packages/docs/api/interfaces/RouterScrollBehavior.md b/packages/docs/api/interfaces/RouterScrollBehavior.md new file mode 100644 index 00000000..499618b2 --- /dev/null +++ b/packages/docs/api/interfaces/RouterScrollBehavior.md @@ -0,0 +1,27 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouterScrollBehavior + +# Interface: RouterScrollBehavior + +## Callable + +### RouterScrollBehavior + +▸ **RouterScrollBehavior**(`to`, `from`, `savedPosition`): `Awaitable`<``false`` \| `void` \| `ScrollPosition`\> + +#### Parameters + +| Name | Type | Description | +| :------ | :------ | :------ | +| `to` | [`RouteLocationNormalized`](RouteLocationNormalized.md) | Route location where we are navigating to | +| `from` | [`RouteLocationNormalizedLoaded`](RouteLocationNormalizedLoaded.md) | Route location where we are navigating from | +| `savedPosition` | ``null`` \| `_ScrollPositionNormalized` | saved position if it exists, `null` otherwise | + +#### Returns + +`Awaitable`<``false`` \| `void` \| `ScrollPosition`\> diff --git a/packages/docs/api/interfaces/RouterViewProps.md b/packages/docs/api/interfaces/RouterViewProps.md new file mode 100644 index 00000000..db1a0ee8 --- /dev/null +++ b/packages/docs/api/interfaces/RouterViewProps.md @@ -0,0 +1,21 @@ +--- +sidebar: "auto" +editLinks: false +sidebarDepth: 3 +--- + +[API Documentation](../index.md) / RouterViewProps + +# Interface: RouterViewProps + +## Properties + +### name + +• `Optional` **name**: `string` + +___ + +### route + +• `Optional` **route**: [`RouteLocationNormalized`](RouteLocationNormalized.md) diff --git a/packages/docs/package.json b/packages/docs/package.json index e22c78ac..ed2a5ef6 100644 --- a/packages/docs/package.json +++ b/packages/docs/package.json @@ -4,7 +4,7 @@ "private": true, "scripts": { "docs": "vitepress dev .", - "docs:api": "node run-typedoc.js", + "docs:api": "node scripts/run-typedoc.js", "docs:build": "vitepress build ." }, "dependencies": { @@ -12,6 +12,8 @@ "vitepress": "^0.20.0" }, "devDependencies": { - "@algolia/client-search": "^4.14.2" + "@algolia/client-search": "^4.14.2", + "typedoc": "^0.23.10", + "typedoc-plugin-markdown": "^3.13.4" } } diff --git a/packages/docs/scripts/run-typedoc.js b/packages/docs/scripts/run-typedoc.js new file mode 100644 index 00000000..68f2cb11 --- /dev/null +++ b/packages/docs/scripts/run-typedoc.js @@ -0,0 +1,11 @@ +const { createTypeDocApp } = require('./typedoc-markdown') +const path = require('path') + +createTypeDocApp({ + name: 'API Documentation', + tsconfig: path.resolve(__dirname, './typedoc.tsconfig.json'), + // entryPointStrategy: 'packages', + githubPages: false, + disableSources: true, + entryPoints: [path.resolve(__dirname, '../../router/src/index.ts')], +}).build() diff --git a/packages/docs/scripts/typedoc-markdown.js b/packages/docs/scripts/typedoc-markdown.js new file mode 100644 index 00000000..d2df4226 --- /dev/null +++ b/packages/docs/scripts/typedoc-markdown.js @@ -0,0 +1,117 @@ +const _fs = require('fs') +const path = require('path') +const TypeDoc = require('typedoc') +const { PageEvent } = TypeDoc +const { + prependYAML, +} = require('typedoc-plugin-markdown/dist/utils/front-matter') + +const fs = _fs.promises + +const DEFAULT_OPTIONS = { + // disableOutputCheck: true, + cleanOutputDir: true, + excludeInternal: true, + readme: 'none', + out: path.resolve(__dirname, '../api'), + entryDocument: 'index.md', + hideBreadcrumbs: false, + hideInPageTOC: true, +} + +/** + * + * @param {Partial} config + */ +exports.createTypeDocApp = function createTypeDocApp(config = {}) { + const options = { + ...DEFAULT_OPTIONS, + ...config, + } + + const app = new TypeDoc.Application() + + // If you want TypeDoc to load tsconfig.json / typedoc.json files + app.options.addReader(new TypeDoc.TSConfigReader()) + // app.options.addReader(new TypeDoc.TypeDocReader()) + + /** @type {'build' | 'serve'} */ + let targetMode = 'build' + + app.renderer.on( + PageEvent.END, + /** + * + * @param {import('typedoc/dist/lib/output/events').PageEvent} page + */ + page => { + console.log(page.url) + if (page.url === 'index.md') { + // strip off the first line because it's the title without the # + page.contents = page.contents.slice(page.contents.indexOf('\n') + 1) + } + page.contents = prependYAML(page.contents, { + sidebar: 'auto', + // TODO: figure out a way to point to the source files? + editLinks: false, + sidebarDepth: 3, + }) + } + ) + + async function serve() { + app.bootstrap(options) + app.convertAndWatch(handleProject) + } + + async function build() { + if ( + (await exists(options.out)) && + (await fs.stat(options.out)).isDirectory() + ) { + await fs.rm(options.out, { recursive: true }) + } + app.bootstrap(options) + const project = app.convert() + return handleProject(project) + } + + /** + * + * @param {import('typedoc').ProjectReflection} project + */ + async function handleProject(project) { + if (project) { + // Rendered docs + try { + await app.generateDocs(project, options.out) + app.logger.info(`generated at ${options.out}.`) + } catch (error) { + app.logger.error(error) + } + } else { + app.logger.error('No project') + } + } + + return { + build, + serve, + /** + * + * @param {'build' | 'serve'} command + */ + setTargetMode(command) { + targetMode = command + }, + } +} + +async function exists(path) { + try { + await fs.access(path) + return true + } catch { + return false + } +} diff --git a/packages/docs/scripts/typedoc.tsconfig.json b/packages/docs/scripts/typedoc.tsconfig.json new file mode 100644 index 00000000..b7727b73 --- /dev/null +++ b/packages/docs/scripts/typedoc.tsconfig.json @@ -0,0 +1,36 @@ +{ + "include": ["../../router/src/**/*.ts"], + "exclude": ["**/*.spec.ts"], + "compilerOptions": { + "baseUrl": "..", + "rootDir": "../..", + "outDir": "dist", + "sourceMap": false, + "noEmit": true, + "paths": { + "vue-router": ["../../vue-router/src"] + }, + + "target": "esnext", + "module": "esnext", + "moduleResolution": "node", + "allowJs": false, + "skipLibCheck": true, + + "noUnusedLocals": true, + "strictNullChecks": true, + "noImplicitAny": true, + "noImplicitThis": true, + "noImplicitReturns": false, + "strict": true, + "isolatedModules": true, + + "experimentalDecorators": true, + "resolveJsonModule": true, + "esModuleInterop": true, + "removeComments": false, + "jsx": "preserve", + "lib": ["esnext", "dom"], + "types": ["jest", "node", "vite/client"] + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index eaa14e42..4f5ebc97 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -34,12 +34,16 @@ importers: specifiers: '@algolia/client-search': ^4.14.2 '@chenfengyuan/vue-countdown': '2' + typedoc: ^0.23.10 + typedoc-plugin-markdown: ^3.13.4 vitepress: ^0.20.0 dependencies: '@chenfengyuan/vue-countdown': 2.0.0 vitepress: 0.20.10_tbpndr44ulefs3hehwpi2mkf2y devDependencies: '@algolia/client-search': 4.14.2 + typedoc: 0.23.10 + typedoc-plugin-markdown: 3.13.4_typedoc@0.23.10 packages/playground: specifiers: @@ -4277,6 +4281,10 @@ packages: hasBin: true dev: true + /jsonc-parser/3.1.0: + resolution: {integrity: sha512-DRf0QjnNeCUds3xTjKlQQ3DpJD51GvDjJfnxUVWg6PZTo2otSm+slzNAxU/35hF8/oJIKoG9slq30JYOsF2azg==} + dev: true + /jsonfile/4.0.0: resolution: {integrity: sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==} optionalDependencies: @@ -4566,6 +4574,10 @@ packages: yallist: 4.0.0 dev: true + /lunr/2.3.9: + resolution: {integrity: sha512-zTU3DaZaF3Rt9rhN3uBMGQD3dD2/vFQqnvZCDv4dl5iOzq2IZQqTxu90r4E5J+nP70J3ilqVCrbho2eWaeW8Ow==} + dev: true + /magic-string/0.25.9: resolution: {integrity: sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ==} dependencies: @@ -4598,6 +4610,12 @@ packages: resolution: {integrity: sha512-CkYQrPYZfWnu/DAmVCpTSX/xHpKZ80eKh2lAkyA6AJTef6bW+6JpbQZN5rofum7da+SyN1bi5ctTm+lTfcCW3g==} dev: true + /marked/4.0.18: + resolution: {integrity: sha512-wbLDJ7Zh0sqA0Vdg6aqlbT+yPxqLblpAZh1mK2+AO2twQkPywvvqQNfEPVwSSRjZ7dZcdeVBIAgiO7MMp3Dszw==} + engines: {node: '>= 12'} + hasBin: true + dev: true + /meow/8.1.2: resolution: {integrity: sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==} engines: {node: '>=10'} @@ -5598,6 +5616,14 @@ packages: engines: {node: '>=8'} dev: true + /shiki/0.10.1: + resolution: {integrity: sha512-VsY7QJVzU51j5o1+DguUd+6vmCmZ5v/6gYu4vyYAhzjuNQU6P/vmSy4uQaOhvje031qQMiW0d2BwgMH52vqMng==} + dependencies: + jsonc-parser: 3.1.0 + vscode-oniguruma: 1.6.2 + vscode-textmate: 5.2.0 + dev: true + /signal-exit/3.0.7: resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==} dev: true @@ -6089,6 +6115,28 @@ packages: is-typedarray: 1.0.0 dev: true + /typedoc-plugin-markdown/3.13.4_typedoc@0.23.10: + resolution: {integrity: sha512-E/EBBmu6ARtnbswZGtBVBB/BfukZiGMOlqPc0RXCI/NFitONBahFqbCAF5fKQlijlcfipJj5pw5AMFH3NytrAw==} + peerDependencies: + typedoc: '>=0.23.0' + dependencies: + handlebars: 4.7.7 + typedoc: 0.23.10 + dev: true + + /typedoc/0.23.10: + resolution: {integrity: sha512-03EUiu/ZuScUBMnY6p0lY+HTH8SwhzvRE3gImoemdPDWXPXlks83UGTx++lyquWeB1MTwm9D9Ca8RIjkK3AFfQ==} + engines: {node: '>= 14.14'} + hasBin: true + peerDependencies: + typescript: 4.6.x || 4.7.x + dependencies: + lunr: 2.3.9 + marked: 4.0.18 + minimatch: 5.1.0 + shiki: 0.10.1 + dev: true + /typescript/4.6.4: resolution: {integrity: sha512-9ia/jWHIEbo49HfjrLGfKbZSuWo9iTMwXO+Ca3pRsSpbsMbc7/IU8NKdCZVRRBafVPGnoJeFL76ZOAA84I9fEg==} engines: {node: '>=4.2.0'} @@ -6211,6 +6259,14 @@ packages: - stylus dev: false + /vscode-oniguruma/1.6.2: + resolution: {integrity: sha512-KH8+KKov5eS/9WhofZR8M8dMHWN2gTxjMsG4jd04YhpbPR91fUj7rYQ2/XjeHCJWbg7X++ApRIU9NUwM2vTvLA==} + dev: true + + /vscode-textmate/5.2.0: + resolution: {integrity: sha512-Uw5ooOQxRASHgu6C7GVvUxisKXfSgW4oFlO+aa+PAkgmH89O3CXxEEzNRNtHSqtXFTl0nAC1uYj0GMSH27uwtQ==} + dev: true + /vue-tsc/0.39.4_typescript@4.7.4: resolution: {integrity: sha512-oGFuAdSt8Q1NatnyyJheW0P/8Sk9RDMWPNzeMHXl1OOnoXrbjz2miMcccujySCpA48+AhzdtyFY1PL0XTPsOSg==} hasBin: true