Skip to content

API ​

This is the lookup reference. Start with your first app to learn the flow, common tasks to choose an API, or container choices to decide navigation ownership.

Creating a router ​

ts
import { createRouter } from 'vue-router-ns'

const router = createRouter({ routes, restore, backPreview: true })
OptionDefaultMeaning
diagnosticsfalsetrue or { maxEvents } for a bounded timeline and native snapshots. See diagnostics.
routesRequiredReadonly array of RouteRecordRaw.
restoreDisabledsave(state), load(), optional maxAge in milliseconds (default: 30 minutes) and stateLimit in bytes per page (default: 8 KiB). See restoration.
backPreviewtrueReveal the previous page during Android 14+ back gestures. false disables it; experimental 'core' tries the proposed Core API with legacy fallback. Requires the platform opt-in.
linksDisabledtrue or { schemes, hosts, map, frame, options, system } to take operating-system URLs. See deep links.

Install once with createApp(App).use(router).start(). This registers the components and provides $router and $route in templates. router.install(app) is the Vue plugin hook.

Router methods ​

to is a RouteLocationRaw: a path string, { path, query?, hash? }, { name, params?, query?, hash? }, or a location relative to the current route. Object locations also accept replace and force. Use force: true to push another instance of the current location. Params belong to named or relative locations, not a path object.

MethodBehavior
push(to, options?)Add a page or present a modal.
replace(to, options?)Replace the current page.
back(options?)Pop one page; close a modal at its root. At a non-modal root it does nothing. Android's system back can still leave the app.
go(delta)Go back by a negative number of pages. Zero and positive values do nothing. Takes no options argument.
backTo(to, options?)Return to the closest matching page below the top; rejects if absent.
backToRoot(options?)Return to the first page in the current stack.
setStack(locations, options?)Reconcile a nonempty list of locations with the stack. Preserves the common prefix; stops at the first failure without rolling back completed steps.
pushForResult<T>(to, options?)Open a page and wait for back({ result }). Resolves to T | undefined when it closes or opening is prevented.
resolve(to)Resolve a location synchronously without navigating. Returns RouteLocation; throws for an unmatched route.
isReady()Promise that settles after initial navigation; does not wait for every hidden tab to load.
openLink(url, options?)Opens a full URL or a bare path the way the OS would: through links, with parents, after the first page and the target stack. Resolves to a LinkResult.
resolveLink(url)The RouteLocation a URL points at under links, or undefined.
onLink(listener)Hears every link the router was handed, taken or not. Returns an unsubscribe function.
setShortcuts(shortcuts)Replaces the home-screen shortcuts (Android dynamic shortcuts, iOS quick actions) with RouteShortcuts that open through openLink. Returns the published ids.
shortcutURL(id, to)Versioned payload for static shortcut resources or app-owned native integration.
pinShortcut(shortcut)Requests Android launcher pinning; true means requested, not user-confirmed.
claimSystemBack(claimant)Lets a native container ({ owns(), back() }) take the Android back and back swipe first, like an open drawer. Returns the release function.

push, replace, back, go, backTo, backToRoot and setStack resolve to NavigationFailure | undefined. Unexpected errors reject; see failures. Back methods have the split-view semantics when called in a split stack.

Retained history ​

history is a readonly ref of NavigationHistory | undefined. getHistory(options?: HistoryOptions) reads a frozen snapshot; HistoryOptions.frame selects a named stack without navigating. The snapshot exposes NavigationHistoryScope and NavigationHistoryEntry data with a detached NavigationHistoryRoute.

backToEntry(target: NavigationHistoryTarget, options?: BackToEntryOptions) selects an exact live entry. Pass a snapshot entry directly. BackToEntryOptions accepts animated and result, with no frame override. It resolves to NavigationFailure | undefined; unavailable addresses and covered modal boundaries reject. See retained history for scope, restoration and concurrency rules.

useBackHistoryMenu(options?: BackHistoryMenuOptions) creates an optional page-owned menu. BackHistoryMenu exposes readonly active, show(source: View): boolean and dismiss(): boolean. See Back history menu for labels, keyboard commands, native fallbacks and lifecycle.

push, replace and pushForResult accept NavigationOptions:

OptionMeaning
frameNamed stack to target. Otherwise use the caller's page stack, or the focused stack outside a page. Does not select a TabView tab.
transitionA name such as 'fade' or a NativeScript transition object; overrides the route default. Includes SharedTransition.
animatedSet false to skip animation.
clearHistoryRemove earlier pages, subject to guards. A split stack retains its list.
propsExtra page props, merged over route-record props. Not persisted by restore.
modaltrue, false, or ModalOptions; overrides the route's presentation.
withParentsPush component-bearing ancestors before the destination.
zoomFromView, element ref, component, or null; native iOS 18+ zoom source.

back, backTo and backToRoot accept BackOptions: animated, frame and result. go(delta) has no options parameter. setStack accepts SetStackOptions: frame, animated and transition; animation applies to the last step only.

Routes and hooks ​

MethodReturn value
addRoute(record) / addRoute(parentName, record)Callback that removes the added route.
removeRoute(name)void. Removes a registered route; does not pop existing pages.
hasRoute(name)boolean.
getRoutes()Normalized RouteRecord[].
beforeEach(guard) / beforeResolve(guard)Callback that unregisters the guard.
afterEach((to, from, failure?) => …)Callback that unregisters the hook.
onError((error, to, from) => …)Callback that unregisters the handler.

A NavigationGuard receives (to, from, { type }), where type is 'push', 'replace' or 'back'. It can return a promise. Return false to abort, a location to redirect, or undefined/true to continue. Guards use return values, not next(). See guards.

Optional middleware and helpers ​

router.addRouteMiddleware(name, guard, { global }?) registers a named middleware and returns its disposer. Destination meta.middleware accepts names/functions or a readonly array. Middleware runs after beforeEach, globals first, then the destination list, before beforeEnter. defineRouteMiddleware(guard) types a function without registering it.

useNavigateTo() captures a helper in page setup, bound to that page's stack. Outside setup use navigateTo(router, to, options?) with explicit context. Both delegate to push/replace and return Promise<NavigationFailure | undefined>. Options: NavigationOptions plus replace. Types: RouteMiddleware, RouteMiddlewareReference, RouteMiddlewareOptions, NavigateTo, NavigateToOptions. See optional middleware and helpers for ordering, disposal, supported conventions and native gesture limits.

State ​

  • currentRoute: readonly ref to the focused route, including the active modal.
  • stack: readonly ref to routes in bottom-to-top order. A page-bound router exposes that page's stack; the exported router follows the focused stack.
  • diagnostics: RouterDiagnostics when enabled; otherwise undefined. See diagnostics.
  • options: the router configuration.
  • START_LOCATION: empty location before initial navigation (path: '/', no matched records).

Locations and route records ​

RouteLocation contains path, fullPath, name, params, query, hash, meta, matched and redirectedFrom. Resolved params are strings or string arrays. Query values are strings, null, or arrays; input query values also accept numbers, booleans and undefined. meta merges parent to child.

RouteRecordRaw accepts path, name (string or symbol), component (component or sync/async loader), children, redirect (location or function), meta, props (true, object or mapper), beforeEnter (guard or array), modal (boolean or ModalOptions) and transition.

Paths support named parameters, optional/repeated parameters and custom patterns. See typed routes. children nests paths and metadata; it does not create nested UI automatically.

ModalOptions forwards NativeScript showModal options except context and closeCallback, which the router owns. Its ios options also accept detents, selectedDetent, largestUndimmedDetent, grabber and cornerRadius. See modals and sheets.

Optional file-routing APIs ​

Node-only vue-router-ns/file-routing/webpack exports the CommonJS-compatible NativeFileRoutesPlugin for webpack 5. vue-router-ns/file-routing/setup exports prepareFileRouting(options), FileRoutingOptions and PreparedFileRouting. These optional build entries generate platform modules and types; their generated installFileRouting(router) registers discovered middleware and handles route-table HMR. See setup and support.

Node-only vue-router-ns/file-routing/vite exports nativeFileRoutes(options) and NativeFileRoutesOptions for Vite 8. Native HMR uses optional adjacent JSON metadata (metadataFiles: true); definePageMeta requires bundled Vite builds while the upstream macro-transform limitation remains. Standalone setup accepts bundler: 'vite'; the default remains webpack.

vue-router-ns/file-routing exports the typed compile-time definePageMeta() macro, PageMeta, PageMetaValue, mergeFileRoutes(generated, explicit) and createFileRouteUpdater(router, routes) (FileRouteUpdater). The updater changes future matching while retaining native entries.

Node-only vue-router-ns/file-routing/generator exports generateFileRoutes(options), writeFileRoutes(options), watchFileRoutes(options, callbacks), transformPageMeta(source, filename) and FileRouteError; types: FileRoutesOptions, GeneratedFileRoutes, FilePage. The compiler peer is optional and needed only by build tooling. See file routing for conventions, metadata restrictions, HMR ownership and integration status.

Optional native layouts ​

createRouter({ layouts, defaultLayout }) registers native layout components/factories per router. defaultLayout defaults to false; meta.layout selects a registered name or opts out with false. The layout owns the root Page and optional ActionBar; the destination supplies its body through the default slot. Layout selection is fixed per entry, with separate layout/content instances for every visit. Unknown names/import failures reject before mounting. See native layouts for lifecycle, HMR, diagnostics and authoring examples.

Route data (experimental) ​

defineRouteLoader(load) infers a data result from (context) => value | PromiseLike<value>. Declare it in meta.loaders; createRouter({ loaders }) optionally registers names for explicit/file-generated metadata. Matched parent and child declarations are additive and deduplicate by definition.

useRouteData(loader) returns per-entry readonly refs data, error, status, a current-attempt ready Promise and reload(). Both promises resolve on success, failure or cancellation; data errors stay in state. Loads start after authorization and do not block native presentation. See data loading for cancellation, lifecycle, cache ownership and native examples.

Exported types: RouteLoader<T>, RouteLoaderContext, RouteLoaderReference, RouteData<T>, RouteDataStatus.

Route code preloading ​

Experimental router.preload(to): RoutePreload prepares only the resolved leaf component's code. useRoutePreload() captures a typed page-owned preparation function in setup. Neither runs guards, data loaders, layouts or native allocation. Actual navigation remains authorized normally and can reuse prepared/in-flight code.

The handle exposes readonly state, ready: Promise<RoutePreloadResult> and cancel(). RoutePreloadState distinguishes queued/loading/ready/error/cancelled; RoutePreloadCancelReason describes cancellation. The promise keeps its first outcome even if a ready lease later expires. router.clearPreloads() invalidates speculative leases without unloading imported modules or the ordinary navigation cache.

RouterOptions.preload?: RoutePreloadOptions configures concurrency (2), maxEntries (16) and ttl (30,000 ms). See code preloading for budgets, ownership, cancellation and authorization limits.

Route data preloading ​

Experimental router.preloadData(to, loader): RoutePreload prepares one declared loader; useRouteDataPreload() captures its page-owned counterpart. defineRouteLoader(load, { preload }) opts a definition in using RouteLoaderOptions / RouteLoaderPreload: a stable object-returning scope() and synchronous authorize({ to, from }). No scope or denied permission produces unauthorized cancellation. Navigation still runs every normal guard.

RouterOptions.preloadData?: RouteDataPreloadOptions supplies separate concurrency, count and TTL budgets. RouteLoaderContext.preloading identifies speculative work. Matching entry creation can reuse data without blocking presentation; reload() uses ordinary loading. clearPreloads() also invalidates data preparation, but does not erase results already consumed by entries or app caches. See data preparation for scope changes, independent consumers, transport cancellation and limits.

Composables ​

FunctionContract
useRouter()Router bound to the current page's stack; app router outside a page. Requires an app using the router.
useRoute(name?)This page's fixed route, or the focused route outside pages. The optional name narrows types; it does not select another route.
onBeforeRouteLeave(guard, { when }?)Page leave guard. when accepts a boolean, ref or getter. Removed on unmount.
onPageActivated(hook)Called when the page becomes visible, including its first activation and returns.
onPageDeactivated(hook)Called when covered. For removal use Vue's onUnmounted.
useBackGesture()Readonly shallow ref to { progress, edge } or null; Android 14+. edge is 'left', 'right' or 'none'.
usePageState(key, options)Keeps JSON-compatible page state across process death: save, restore(value, { version, page }), optional version and migrate. Needs restore on the router. See page state.
useNativeFlow(flow)Binds a NativeFlow (a system picker, another app's activity) to the page: run(input, { before }) resolves once with completed, cancelled or failed; running ref. createDocumentPicker() is the built-in flow. See native flows.

Register page hooks in the routed component's setup. In an expanded split view, both list and top detail are active. See page lifecycle and HMR.

Components ​

ComponentProps and slots
RouterViewname ('default'), initial ('/'), backToRootOnReselect (false). Mounts one Frame.
RouterSplitViewRequired list; name ('default'), breakpoint (840), listWidth (320), foldAware (true, Android), backToRootOnReselect (false). Slot: empty.
RouterUIKitSplitViewRequired list; name ('default'), primaryWidthFraction (0.32). Window-root UIKit primary/secondary columns, iOS 18+ with Core SplitView. See UIKit columns.
RouterDrawerwidth (300), open (v-model:open), closeOnNavigate (true). Slots: default content and drawer. Events opened, closed; ref open(), close(), toggle(), isOpen. Android only; iOS renders the content. See Android drawer.
RouterTabsselected (v-model:selected, a tab name), canSelect(name), sidebar (iOS 18+), minimize ('never', iOS 26 'onScrollDown'/'onScrollUp'), rail (600, Android); tabBackgroundColor, tabTextColor, selectedTabTextColor, labelVisibility (Material). Events select, reselect. Children: RouterTab with name, title, icon (SF Symbol), androidIcon, badge, role. See tabs.
RouterLinkRequired to; replace, clearHistory, withParents, zoom (all false); transition, frame; menu (RouteMenuOptions: a long press previews the route). One default-slot child; slot receives { navigate }. Adds a tap handler without a native wrapper.
DeferredNo props. Slots: default content and fallback. Shows content after the page's first activation and keeps it mounted afterward. Outside a routed page, renders immediately.

v-route-preview (exported as vRoutePreview, registered by install) takes RoutePreviewOptions on any view: to, preview, props, canPreview, size, actions, openTitle and the navigation options. attachRouteMenu(view, router, options) and detachRouteMenu(view) do the same without Vue. See context menu previews.

Router view names must be unique, including split views. name and the initial route (initial/list) are read at mount; use a new Vue key to create a different stack. Split view dimensions are device-independent pixels; list width is capped at half the available width. See split view.

Failures and exported types ​

isNavigationFailure(value, type?) identifies a NavigationFailure (Error with type, to, from). NavigationFailureType has aborted (4), cancelled (8), and duplicated (16); the optional type argument also accepts a bitmask.

Public types are exported from the package root:

  • Tabs: RouterTabDescriptor, TabMinimize, TabRole, TabLabelVisibility, TabBarVisibility; supportsNativeTabs().
  • Router configuration: Router, RouterOptions, SystemBackClaimant, RouterDrawerHandle, RestoreOptions, SavedStacks, SavedEntry, SavedState, PageStateOptions, PageStateContext.
  • Routes: RouteRecordRaw, RouteRecord, RouteRecordName, RouteMeta, RouteProps, RouteComponent, RawRouteComponent, Lazy.
  • Locations: RouteLocation, RouteLocationRaw, RouteLocationPathRaw, RouteLocationNamedRaw, RouteLocationRelativeRaw, RouteParams, RouteParamsRaw, RouteParamValue, RouteParamValueRaw, LocationQuery, LocationQueryRaw, LocationQueryValue, LocationQueryValueRaw.
  • Navigation: NavigationOptions, BackOptions, SetStackOptions, NavigationType, NavigationInfo, NavigationGuard, NavigationGuardReturn, NavigationHookAfter, NavigationErrorHandler, NavigationFailure, LeaveGuardOptions.
  • Native flows: NativeFlow, NativeFlowContext, NativeFlowOutcome, NativeFlowHandle, NativeFlowRunOptions, DocumentPickerInput, DocumentPickerResult; startNativeFlow(flow, input, page) runs one outside a page.
  • Links: LinksOptions, LinkOptions, LinkWindow, InitialLinkRequest, IncomingLink, LinkResult, LinkIgnoredReason, LinkSource, LinkListener, RouteShortcut. supportsShortcuts() reports whether the platform shows home-screen shortcuts.
  • Native presentation: ModalOptions, SheetOptions, SheetDetent, AndroidModalOptions, BottomSheetOptions, BottomSheetState, TransitionOption, ZoomSource, BackGesture, BackGestureEdge. supportsBottomSheets() reports whether the Android build includes Material.
  • Inferred route types: Register, RegisteredRouter, RouteMapFrom, RouteMapGeneric, RouteNames, RouteLocationOf, RouteLocationRawOf, ParamsFromPath.

Augment Register and RouteMeta as shown in typed routes.

Diagnostics ​

RouterDiagnostics exposes routerId, stopped, events, droppedEvents, snapshot(), subscribe(listener), toJSON(), export(), clear() and stop(). Data is readonly, bounded and redacted; stop() releases live sources. Exported types: DiagnosticsOptions, RouterDiagnostics, DiagnosticsExport, DiagnosticSnapshot, DiagnosticStack, DiagnosticHost, DiagnosticEntry, DiagnosticIssue, DiagnosticIssueCode, DiagnosticEvent, DiagnosticPhase and DiagnosticOutcome. See diagnostics for format, timing semantics and lifetime.

recording() returns an opt-in experimental v2 recording; checkpoint() explicitly observes the current state. Configure diagnostics.recording with a boolean or DiagnosticRecordingOptions. Additional readonly types: DiagnosticsRecording, DiagnosticRecord, DiagnosticBoundary, DiagnosticObservation. Existing v1 exports remain unchanged. See the recording contract for byte limits, gaps and the current viewer boundary.

useNativeSearch(options) registers page-owned native search. Exports: NativeSearchOptions, NativeSearch. See native bars and search for query ownership, activation and platform differences.

Page actions ​

usePageActions(source, { onError? }) shares typed, page-owned callbacks and reactive state between PageActionItem and route menus. Exports: PageAction, PageActionContext, PageActionState, PageActions, PageActionsOptions. See page actions for execution, cancellation, ownership and optional keyboard reuse.

Keyboard commands ​

useNavigationCommands(source) and NavigationCommandScope bind opt-in commands to a page/window. Types: NavigationCommand, NavigationCommandState, NavigationCommands, NavigationShortcut, KeyModifier. See keyboard commands.

Accessibility and motion ​

useNavigationFocus(options) supplies opt-in initial/return accessibility targets and modal initiator restoration. Types: NavigationFocus, NavigationFocusOptions, NavigationFocusTarget. RouterOptions.motion accepts MotionPolicy (system, reduced, full); default system. See accessibility and motion.

Native hosts (experimental) ​

mountNativeHost(router, name, host, initial?) drives a stack in a NativeHost and returns its unmount function. useNativeHost<TNative>() gives a page the kind, capabilities and native container of its host. createFrameHost(frame, { modal? }) and createSplitFrameHost(list, detail, { expanded, detailVisible }) are the built-in hosts; NATIVE_HOST_VERSION is the contract version the router accepts. Types: NativeHost, NativeHostCapabilities, NativeHostDelegate, NativeHostPushOptions, NativeHostBackOptions, NativeHostPart, NativeHostRole, NativeHostHandle, NativeHostVersion, FrameHostOptions, SplitFrameHostOptions, SplitFrames, BackGestureSession, BackPreview. See native hosts.

defineNativeDestination<Input, Output>({ id, input, ios?, android? }) returns a route component containing an existing UIKit controller or AndroidX Fragment. Factories return { native, dispose? }; their context supplies input, route, page, complete(value), cancel(), dismissed() and beforeLeave(guard). Types: NativeDestinationOptions, NativeDestinationContext, NativeDestinationInstance. See native destinations for containment, guard limits and restoration.

supportsUIKitSplitView() checks whether the optional UIKit backend is available.

Native windows (experimental, core 9.1+) ​

RouterOptions.window?: RouterWindow binds one router to a native window; otherwise the first mounted view supplies its owner. router.window is a readonly ref to that owner. router.openWindow(to, options?: OpenWindowOptions): void resolves a typed location and requests an OS window. OpenWindowOptions.data carries serializable app metadata. getWindowRoute(data) reads its path in a window content resolver.

RestoreOptions.key supplies a stable application snapshot key. Scoped callbacks receive optional RestoreContext (windowId, key) in save(state, context) and load(context). Scoped SavedStacks includes windowKey; a mismatch is ignored. RouterWindow is a structural subset of NativeWindow so the package declarations remain usable with older supported core versions. See native windows for bootstrapping, lifecycle, configuration and limits.

The optional vue-router-ns/system-search entry point exports createSystemSearch, SystemSearch, SystemSearchOptions and SearchItem. supportsPinnedShortcuts() is exported from the package root. See deep links.

Additional exported types and metadata parsing ​

ExportContract
RouteMenuActionNative context-menu action descriptor; see context menus.
SearchBarPlacement'automatic', 'stacked', 'inline' or 'integrated' for the supported UIKit search placement. Availability remains platform-dependent.
DrawerPresentationRequested 'overlay', 'permanent' or 'auto' mode.
ResolvedDrawerPresentationEffective 'overlay' or 'permanent' mode reported by the drawer handle and presentation event.
UIKitSplitFramesExperimental native-host payload extending SplitFrames with readonly view: UIKitSplitView.
PageMetaTransformExperimental generator result: hasMacro, metadata, transformed code and its source map.

The experimental Node-only vue-router-ns/file-routing/generator entry also exports parsePageMetadataJson(source, filename): PageMeta. It validates a JSON metadata object and throws FileRouteError for invalid or unsupported metadata. Use it when integrating adjacent metadata files; it does not execute route code.

Released under the MIT License.