@molecule/app-routing-vue-router

Provider bond · routing · App (browser) · v1.4.1 · Apache-2.0

Vue Router provider for @molecule/app-routing

npm install @molecule/app-routing-vue-router

npm · Source on GitHub · Implements @molecule/app-routing

How it works

@molecule/app-routing-vue-router is a provider bond on the app (browser) side: it implements the routing core interface (@molecule/app-routing) with a concrete vendor or library behind it.

Your code calls the core; you wire this provider once at startup. Swapping vendors later is one line in that wiring, not a rewrite.

<!-- App.vue (or a root-level component INSIDE the vue-router app) -->
<script setup lang="ts">
import { useLocation, useMoleculeRouterProvider } from '@molecule/app-routing-vue-router'

// Builds the adapter from vue-router's useRouter()/useRoute() AND bonds it, so
// molecule packages using @molecule/app-routing share THIS router. No manual
// setRouter watch needed.
const router = useMoleculeRouterProvider()

const location = useLocation()
function goToProfile() {
  router.value.navigate('/profile')
}
</script>

<template>
  <p>Current path: {{ location.pathname }}</p>
  <button @click="goToProfile">Go to Profile</button>
</template>

Works with: @molecule/app-bond, @molecule/app-i18n, @molecule/app-routing, @molecule/app-vue

Reference

Vue Router provider for @molecule/app-routing.

This package provides a Vue Router implementation of the molecule Router interface, allowing you to use molecule's routing abstractions with Vue Router.

With HTTP and auth clients bonded, the router createVueRouter({ router }) builds replaces the current URL with /login after a credential-free GET receives a 401 and the session is confirmed signed out, as React's BrowserRouter does. location.state.from holds the original location. Set signInPath to use a different sign-in route or pass signInPath: false to opt out.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

<!-- App.vue (or a root-level component INSIDE the vue-router app) -->
<script setup lang="ts">
import { useLocation, useMoleculeRouterProvider } from '@molecule/app-routing-vue-router'

// Builds the adapter from vue-router's useRouter()/useRoute() AND bonds it, so
// molecule packages using @molecule/app-routing share THIS router. No manual
// setRouter watch needed.
const router = useMoleculeRouterProvider()

const location = useLocation()
function goToProfile() {
  router.value.navigate('/profile')
}
</script>

<template>
  <p>Current path: {{ location.pathname }}</p>
  <button @click="goToProfile">Go to Profile</button>
</template>

Type

provider

Installation

npm install @molecule/app-routing-vue-router @molecule/app-bond @molecule/app-i18n @molecule/app-routing @molecule/app-vue vue vue-router

API

Interfaces

ListRouteNavItem

A named list view and its navigation label.

interface ListRouteNavItem extends ListRouteSelection {
  /** Translated label, optionally including an icon. */
  label: VNodeChild
  /** Path parameters for this destination; current route parameters are otherwise retained. */
  params?: RouteParams
  /** Keep the choice visible but prevent navigation. Authorization still belongs in the route. */
  disabled?: boolean
}

ListRouteNavItemState

URL-derived state available to the app's link styling.

interface ListRouteNavItemState<Selection extends string = string> {
  /** The app-owned selection key. */
  selection: Selection
  /** Whether the current URL selects this view. */
  active: boolean
  /** Whether navigation is disabled for this choice. */
  disabled: boolean
}

ListRouteNavProps

Props for URL-backed list navigation; local content panels use the UI package's Tabs instead.

It carries every native <nav> attribute React's prop type does (id, class, event listeners), so one declaration serves both bonds; Vue's attribute fallthrough puts them on the navigation landmark.

interface ListRouteNavProps<Selection extends string = string> extends Omit<
  HTMLAttributes,
  'aria-label' | 'children'
> {
  /** Accessible navigation name, translated by the app. */
  'aria-label': string
  /** Every declared view stays visible on every route; labels and targets share one declaration. */
  selections: Record<Selection, ListRouteNavItem>
  /** Tie-breaker or fallback, with the same meaning as useListRoute's defaultSelection. */
  defaultSelection?: NoInfer<Selection>
  /** Pagination query key to remove on selection, defaulting to page. */
  pageParam?: string
  /** Required for protected selections, with the same readiness rules as useListRoute. */
  auth?: ListRouteAuth
  /** Render links in a list, with optional classes for the list and its items. */
  list?: { className?: string; itemClassName?: string }
  /** App-owned styling, resolved from its class map. */
  linkClassName?: string | ((state: ListRouteNavItemState<Selection>) => string | undefined)
  /** Render the list beside the nav using its exact URL state, including resolved item params. */
  children?: (route: ListRouteResult<string, Selection>) => VNodeChild
}

MoleculeRouterProviderProps

Props for MoleculeRouterProvider.

interface MoleculeRouterProviderProps {
  /**
   * Optional route definitions for molecule named routes. Pass a stable array; a later,
   * different array registers onto the same router.
   */
  routes?: RouteDefinition[]

  /**
   * Optional callback invoked ONCE with the bonded router, after it is bonded, so a guard
   * or subscription can be registered.
   */
  onRouterReady?: (router: Router) => void
}

LazyPageOptions

Options for lazyPage.

interface LazyPageOptions {
  /** What the page's area shows while its code loads. Defaults to nothing. */
  fallback?: Component
}

VueRouterConfig

Vue Router-specific configuration.

interface VueRouterConfig {
  /**
   * Vue Router instance (from useRouter).
   */
  router?: VueRouterInstance

  /**
   * Current route (from useRoute).
   * @deprecated The router's `currentRoute` is read instead, so the location stays current
   * after every navigation. Accepted for existing apps; unused.
   */
  route?: RouteLocationNormalizedLoaded

  /**
   * Initial route definitions for named routes.
   */
  routes?: RouteDefinition[]

  /**
   * Path to replace the current location with on a signed-out GET 401. Defaults to
   * `/login`; `false` turns the redirect off. Applies only with a `router`.
   */
  signInPath?: string | false
}

VueRouterComposable

Vue Router composable return type.

interface VueRouterComposable {
  /**
   * Vue Router instance.
   */
  router: VueRouterInstance

  /**
   * Current route.
   */
  route: RouteLocationNormalizedLoaded
}

ListRouteFilter

Where a list filter lives in the URL. Path values take precedence over query values.

interface ListRouteFilter {
  /** Query key; defaults to the filter's name when `param` is absent. */
  query?: string
  /** Path parameter supplied by the current route, such as `category` in `/topics/:category`. */
  param?: string
  /** Value returned when neither URL source supplies a value; omitted from generated queries. */
  defaultValue?: string
}

ListRouteSelection

A selectable list view, expressed in the app's own route contract.

interface ListRouteSelection {
  /** Absolute route pattern, for example `/members/:member/saved`. */
  path: string
  /** Query values identifying this view. An undefined value requires the key to be absent. */
  query?: QueryParams
  /** A protected selection never loads before authentication is confirmed. */
  requiresAuth?: boolean
}

ListRouteAuth

Authentication readiness for protected list selections.

interface ListRouteAuth {
  /** The auth client's status. Unavailable is distinct from a signed-out session. */
  status: 'loading' | 'authenticated' | 'unauthenticated' | 'unavailable'
  /** App-owned sign-in URL. A signed-out protected visit replaces history with this URL. */
  redirectTo: string
}

ListRouteOptions

URL-backed list state configuration; it neither invents nor rewrites the app's route contract.

interface ListRouteOptions<Filter extends string = string, Selection extends string = string> {
  /** Fixed number of items per page; defaults to 20. */
  pageSize?: number
  /** Query key for a 1-indexed page; defaults to `page`. Page one omits the key. */
  pageParam?: string
  /** Route pattern for changing path-backed filters when no selections are configured. */
  path?: string
  /** Filters and their URL sources. API-only filters do not belong here. */
  filters?: Record<Filter, ListRouteFilter>
  /** Named views sharing a list. Both path variants and query variants are supported. */
  selections?: Record<Selection, ListRouteSelection>
  /** Tie-breaker when multiple selections match, or fallback when none matches. */
  defaultSelection?: NoInfer<Selection>
  /** Required when a selection is protected. Public views remain public as auth changes. */
  auth?: ListRouteAuth
}

ListRouteChange

A single atomic list navigation. Filter/selection changes reset page unless explicitly supplied.

interface ListRouteChange<Filter extends string = string, Selection extends string = string> {
  /** Target page, starting at one. */
  page?: number
  /** Patch of URL filter values. Undefined removes a query filter. */
  filters?: Partial<Record<Filter, string | undefined>>
  /** Target view, resolved through its configured path and query values. */
  selection?: Selection
  /** Optional path parameter changes, for example when opening a different member's saved view. */
  params?: RouteParams
}

ListRouteResult

List state and navigation, derived directly from the current location.

interface ListRouteResult<Filter extends string = string, Selection extends string = string> {
  /** Current 1-indexed page; malformed and non-positive URL values read as page one. */
  page: number
  /** Configured items per page. */
  pageSize: number
  /** Zero-indexed item offset for an API request. */
  offset: number
  /** Current URL filter values, including values supplied by path parameters. */
  filters: Record<Filter, string | undefined>
  /** Matching view, or the configured fallback. */
  selection: Selection | undefined
  /** Decoded current path parameters, also usable as API-only filters. */
  params: RouteParams
  /** False while a protected selection is awaiting auth, signed out, or unavailable. */
  canLoad: boolean
  /** Readiness for the current view. A public view always stays ready. */
  status: 'ready' | 'loading' | 'unauthenticated' | 'unavailable'
  /** Sign-in destination while a signed-out protected view is being redirected. */
  redirectTo: string | undefined
  /** Build a real link target, preserving the current pathname, unrelated query values and hash. */
  href: (change?: ListRouteChange<Filter, Selection>) => string
  /** Navigate atomically. Location state is preserved unless options explicitly replace it. */
  navigate: (change: ListRouteChange<Filter, Selection>, options?: NavigateOptions) => void
  /** Change only the page, retaining the current filters and view. */
  setPage: (page: number, options?: NavigateOptions) => void
  /** Patch URL filters and return to page one. */
  setFilters: (
    filters: Partial<Record<Filter, string | undefined>>,
    options?: NavigateOptions,
  ) => void
  /** Select a configured view at page one, preserving current route parameters. */
  select: (selection: Selection, options?: NavigateOptions) => void
}

RouteLocation

Current URL decomposed into pathname, search string, hash, navigation state, and unique key.

interface RouteLocation {
  /**
   * Current pathname.
   */
  pathname: string

  /**
   * Query string (including leading ?).
   */
  search: string

  /**
   * Hash (including leading #).
   */
  hash: string

  /**
   * State data passed with navigation.
   */
  state?: unknown

  /**
   * Unique key for this location.
   */
  key?: string
}

RouteMatch

Result of matching a URL against a route pattern (path, params, query string).

interface RouteMatch<Params extends RouteParams = RouteParams> {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Matched URL pathname.
   */
  pathname: string

  /**
   * Route parameters.
   */
  params: Params

  /**
   * Whether this is an exact match.
   */
  isExact: boolean
}

Options for programmatic navigation (replace vs push, carry state, preserve query/hash).

interface NavigateOptions {
  /**
   * Replace current history entry instead of pushing.
   */
  replace?: boolean

  /**
   * State to pass with navigation.
   */
  state?: unknown

  /**
   * Preserve current query params.
   */
  preserveQuery?: boolean

  /**
   * Preserve current hash.
   */
  preserveHash?: boolean
}

RouteDefinition

Route configuration entry (path pattern, name, auth requirements, roles, children).

interface RouteDefinition {
  /**
   * Route path pattern.
   */
  path: string

  /**
   * Route name (for named routes).
   */
  name?: string

  /**
   * Whether the route requires exact matching.
   */
  exact?: boolean

  /**
   * Whether the route requires authentication.
   */
  requiresAuth?: boolean

  /**
   * Required roles/permissions.
   */
  roles?: string[]

  /**
   * Route metadata.
   */
  meta?: Record<string, unknown>

  /**
   * Child routes.
   */
  children?: RouteDefinition[]
}

Router

Client-side router providing navigation, guards, route matching, and history control.

All routing providers must implement this interface.

interface Router {
  /**
   * Returns the current route location (pathname, search, hash, state).
   */
  getLocation(): RouteLocation

  /**
   * Gets the current route params.
   */
  getParams<T extends RouteParams = RouteParams>(): T

  /**
   * Gets the current query params.
   */
  getQuery(): QueryParams

  /**
   * Gets a specific query parameter.
   */
  getQueryParam(key: string): string | undefined

  /**
   * Gets the current hash.
   */
  getHash(): string

  /**
   * Navigates to a path. A path that is only a query or a hash (`'?tab=2'`, `'#top'`) stays on
   * the current page, as React Router's `navigate` does; a hash alone drops the current query.
   */
  navigate(path: string, options?: NavigateOptions): void

  /**
   * Navigates to a named route.
   */
  navigateTo(
    name: string,
    params?: RouteParams,
    query?: QueryParams,
    options?: NavigateOptions,
  ): void

  /**
   * Goes back in history.
   */
  back(): void

  /**
   * Goes forward in history.
   */
  forward(): void

  /**
   * Goes to a specific point in history.
   */
  go(delta: number): void

  /**
   * Updates the current query params.
   */
  setQuery(params: QueryParams, options?: NavigateOptions): void

  /**
   * Updates a specific query parameter.
   */
  setQueryParam(key: string, value: string | undefined, options?: NavigateOptions): void

  /**
   * Updates the current hash.
   */
  setHash(hash: string, options?: NavigateOptions): void

  /**
   * Checks if a path matches the current location.
   *
   * @returns `true` if the path matches the current route.
   */
  isActive(path: string, exact?: boolean): boolean

  /**
   * Matches a path pattern against a pathname.
   */
  matchPath<Params extends RouteParams = RouteParams>(
    pattern: string,
    pathname: string,
  ): RouteMatch<Params> | null

  /**
   * Generates a URL from a named route.
   */
  generatePath(name: string, params?: RouteParams, query?: QueryParams): string

  /**
   * The `href` an anchor to the in-app `path` carries, as the native router's own link
   * writes it (its base path prefixed, or `#/…` under a hash history), so a middle-click,
   * a new tab or a copied link opens the same page a click does. A `path` that is only a
   * query or a hash (`'?tab=2'`, `'#top'`) is the current page's, as `navigate` reads it
   * and as React Router's `<Link>` writes it: `'#top'` on `/docs?x=1` is `/docs#top`.
   *
   * @param path - Pathname with optional query string and hash, as passed to `navigate`.
   * @returns The `href`.
   */
  createHref(path: string): string

  /**
   * Calls `listener` once after each navigation the router commits, however it started (a
   * link, the back button, `navigate`), with the new location and the navigation action.
   * A router calls it before the browser paints the new page, so a component that renders
   * from a listener (the framework bindings' `useLocation` and `useParams` do) shows the new
   * location in the same paint as the new page. Molecule's router conformance tests check
   * that at every paint.
   *
   * @param listener - Called with the new location and the navigation action.
   * @returns Stops calling `listener`.
   */
  subscribe(listener: RouteChangeListener): () => void

  /**
   * Adds a navigation guard.
   */
  addGuard(guard: NavigationGuard): () => void

  /**
   * Registers route definitions.
   */
  registerRoutes(routes: RouteDefinition[]): void

  /**
   * Gets all registered routes.
   */
  getRoutes(): RouteDefinition[]

  /**
   * Destroys the router.
   */
  destroy(): void
}

RouterConfig (deprecated)

Deprecated: Use BrowserRouterConfig (createBrowserRouter) or MemoryRouterConfig (createMemoryRouter): each takes only the options it acts on.

Configuration options for creating a router instance.

interface RouterConfig {
  /**
   * Router mode.
   */
  mode?: 'history' | 'hash' | 'memory'

  /**
   * Base path.
   */
  basePath?: string

  /**
   * Initial routes.
   */
  routes?: RouteDefinition[]
}

Types

LazyLoadableComponent

Any component a lazy page can load.

type LazyLoadableComponent = Component

VueRouteParamName

The parameter names a Vue Router path declares, required and optional together.

type VueRouteParamName<Path extends string> =
  VueRouteLinkNames<Path>['required'] | VueRouteLinkNames<Path>['optional']

VueRouteParams

The parameters a Vue Router path declares. Every value is a string, or undefined when the URL leaves the parameter out.

type VueRouteParams<Path extends string> = Readonly<{
  [Name in VueRouteParamName<Path>]: string | undefined
}>

RouteParams

URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).

type RouteParams = Record<string, string>

QueryParams

URL query string parameter map (single values or arrays for repeated keys).

type QueryParams = Record<string, string | string[] | undefined>

GuardResult

Navigation guard result.

type GuardResult = boolean | string | { path: string; replace?: boolean } | void

Navigation guard function invoked before each navigation. Return false to cancel, a string/path to redirect, or void to allow.

type NavigationGuard = (
  to: RouteLocation,
  from: RouteLocation | null,
) => GuardResult | Promise<GuardResult>
  • to — The target route location being navigated to.
  • from — The current route location being navigated away from, or null on initial load.

RouteChangeListener

Callback invoked on each route change with the new location and the navigation action that triggered it.

type RouteChangeListener = (location: RouteLocation, action: NavigationAction) => void

Functions

useMoleculeRouter(routes)

Composable to get the molecule Router for the current Vue Router.

Returns the router a mounted MoleculeRouterProvider provides exactly; without one it creates ONE router for the calling Vue Router instance and reuses it for the app's lifetime. Passing routes registers them for molecule named routes: the first array creates the router with them, and a later, different array registers onto the same router.

function useMoleculeRouter(routes?: RouteDefinition[]): ComputedRef<Router>
  • routes — Optional route definitions for named routes.

Returns: The reactive molecule Router ref.

useMoleculeRouterProvider(routes)

Composable that builds the molecule Router from Vue Router AND bonds it as the active singleton via @molecule/app-routing's setRouter.

Call this ONCE near the app root (e.g. in App.vue's setup). One Vue Router gets one molecule Router for the app's lifetime, so setRouter runs once, synchronously in setup, and @molecule/app-routing's navigate()/getRouter() drive the REAL Vue Router (not the core's auto-created fallback browser router) for the rest of the app. Returns the same reactive router ref so you can also use it locally.

function useMoleculeRouterProvider(routes?: RouteDefinition[]): ComputedRef<Router>
  • routes — Optional route definitions for molecule named routes.

Returns: The reactive molecule Router ref (already bonded).

useLocation() (deprecated)

Deprecated: The name collides with @molecule/app-vue's. Use useMoleculeRouter() and read getLocation() from it instead.

Composable to get the current location as a reactive ref.

function useLocation(): ComputedRef<RouteLocation>

Returns: Reactive location ref

useParams() (deprecated)

Deprecated: The name collides with @molecule/app-vue's. Use useMoleculeRouter() and read getParams() from it instead.

Composable to get route params as a reactive ref.

function useParams<T extends RouteParams = RouteParams>(): ComputedRef<T>

Returns: Reactive params ref

useQuery() (deprecated)

Deprecated: The name collides with @molecule/app-vue's. Use useMoleculeQuery instead, which returns the same reactive query.

Composable to get query params as a reactive ref.

function useQuery(): ComputedRef<QueryParams>

Returns: Reactive query params ref

useNavigate() (deprecated)

Deprecated: The name collides with @molecule/app-vue's. Use useMoleculeNavigate instead, which takes molecule's own NavigateOptions (replace, state, preserveQuery, preserveHash).

Composable to get a navigate function.

function useNavigate(): (path: string, options?: NavigateOptions) => void

Returns: Navigate function

useIsActive(path, exact)

Composable to check if a path is active.

function useIsActive(path: string, exact?: boolean): ComputedRef<boolean>
  • path — Path to check
  • exact — Whether to require exact match

Returns: Reactive boolean ref

useRouteChange(callback)

Composable to subscribe to route changes.

function useRouteChange(
  callback: (location: RouteLocation, action: 'push' | 'replace' | 'pop') => void,
): void
  • callback — Callback to run on route change

useNavigationGuard(guard)

Composable to add a navigation guard.

function useNavigationGuard(
  guard: (
    to: RouteLocation,
    from: RouteLocation | null,
  ) =>
    | boolean
    | string
    | { path: string; replace?: boolean }
    | void
    | Promise<boolean | string | { path: string; replace?: boolean } | void>,
): void
  • guard — Guard function

defineRoute(path, page)

Register a literal Vue Router path and give its page the params that path declares.

Create the route at module scope and add it to the routes passed to createRouter. The render callback returns the page's vnodes and runs again when the params change. Pass { Component: EditPage } to give the page a typed params prop automatically. A render callback can also supply app-owned props, such as a view selected by a literal suffix. Keep page hooks inside the page component. In nested routes, layout components own the params declared on their own paths.

Use the returned href for links and post-save navigation. It builds the destination from the same path that mounts the page, with the parameter names required by that path, and writes it the way Vue Router writes a URL. Pass values from the saved response when identity can change. A repeated parameter (:name+, :name*) takes one string joined with /, and an omitted optional parameter is left out of the link.

function defineRoute<const Path extends string>(
  path: Path,
  page: RoutePage<Path>,
): RouteRecordRaw & { path: Path; href: (...[params]: LinkArgs<Path>) => string }
  • path — A route path, including any named parameters.
  • page — A component receiving params, or a function building the page's vnodes.

Returns: The route table entry and a function that builds a link to it.

vueRouterHistory(router)

Builds a molecule RouterHistory over a Vue Router instance, for createHistoryRouter(vueRouterHistory(router), { routes }).

The location is read from the router's live currentRoute at every call, navigations go through router.push/replace/go, and listeners hear every navigation Vue Router commits — its own links, the browser's back button, and pushes made through the molecule router — exactly once each. Navigations Vue Router refused (a cancelled or duplicated navigation, reported to afterEach as a failure) notify nothing.

function vueRouterHistory(router: VueRouterInstance): RouterHistory
  • router — The Vue Router instance (from createRouter or useRouter).

Returns: The history for createHistoryRouter.

lazyPage(load, options)

Load a route's page on demand, each page inside a fallback of its own.

Use it instead of defineAsyncComponent for every page a route names. Navigating to a page whose code has not loaded yet then replaces the previous page at once: the previous page unmounts and the new page shows fallback until its code arrives. A page loaded through defineAsyncComponent (suspensible by default) instead suspends into the nearest <Suspense>: when the boundary's own content is the page, it keeps the previous page's content mounted while the new one is pending, so the URL already names the new page while the old page is still there. Layout routes (an app shell around <RouterView>) stay mounted either way.

The page's code is loaded with suspensible: false and delay: 0, so the fallback is what renders while the code is on its way instead of an empty page that waits for the shared boundary. Do not give the async component to a route record directly: Vue Router warns (VUE_ROUTER_R0029) and handles loading itself; this returns the plain wrapper component a route record should name.

function lazyPage<Page extends LazyLoadableComponent>(
  load: () => Promise<{ default: Page }>,
  options?: LazyPageOptions,
): DefineSetupFnComponent<ComponentProps<Page>>
  • load — Loads the page module, as for defineAsyncComponent: () => import('./pages/Article.js').then((m) => ({ default: m.Article })).
  • options — Optional fallback shown in the page's area while its code loads.

Returns: A component to use as a route record's component: { path: '/article/:slug', component: lazyPage(load, { fallback }) }.

createVueRouter(config)

Creates a molecule Router that drives a Vue Router instance.

Guards, named routes and query/hash management are the ones every routing bond shares (createHistoryRouter); the location always reads Vue Router's live currentRoute, so it never goes stale after a navigation, and subscribers hear Vue Router's own navigations (links, the back button) too — not only navigate calls made here.

Without a router (no Vue Router instance yet), the core's browser router is returned, without the sign-in rule.

function createVueRouter(config?: VueRouterConfig): Router
  • config — The Vue Router instance, optional route definitions for molecule named routes, and (accepted but unused, see VueRouterConfig.route) a current route snapshot.

Returns: A molecule Router with navigation, guards, query/hash management, and route matching.

useConsumedSearchParam(name)

Consume a credential query parameter into composable state and remove only that parameter from the address through Vue Router. The value survives local re-renders, failed-submit retries and later query-only navigation; a newly arriving value on the same mounted route is consumed too and shows one commit later. Path, hash, unrelated query values and router location state are retained, and Back/Forward restore the value consumed on each entry.

Vue Router owns the URL replacement, so the molecule router's location and window.location agree.

function useConsumedSearchParam(
  name: string,
): ComputedRef<readonly [string, (value: string) => void]>
  • name — The credential query key to consume, for example token or code.

Returns: A computed ref of the consumed value ('' before first consumption) and a state setter; the form clears it after a successful submit.

useListRoute(options)

Own URL-backed pagination, filters and selected views without mirrored state or navigation effects. Works inside any Vue Router router — a plain createRouter app with no molecule provider, or one wrapped in MoleculeRouterProvider. Ordinary links, direct visits, and Back/Forward all read the same URL. Page links retain path parameters and unrelated queries; changing filters or views resets the page atomically. Protected views wait for auth and redirect only a confirmed signed-out session, with state.returnTo set.

The options may be reactive (a ref, a reactive object or a getter), so an auth status going from loading to unauthenticated performs the sign-in redirect on the same component, the way React re-renders useListRoute with new options.

function useListRoute<Filter extends string = string, Selection extends string = string>(
  options?: MaybeRefOrGetter<ListRouteOptions<Filter, Selection>>,
): ComputedRef<ListRouteResult<Filter, Selection>>
  • options — App-owned filter sources, view paths, pagination and optional auth readiness.

Returns: A computed ref of the list state plus link builders and navigation actions. Gate data queries with canLoad.

useMoleculeNavigate()

Composable to get a navigate function backed by the bound molecule Router, usable inside any Vue Router app with or without MoleculeRouterProvider.

The returned function accepts molecule's own NavigateOptions (replace, state, preserveQuery, preserveHash) and drives the native Vue Router.

function useMoleculeNavigate(): Router['navigate']

Returns: The navigate function.

useMoleculeQuery()

Composable to get the current query params as a reactive ref, usable inside any Vue Router app with or without MoleculeRouterProvider.

The ref reads the live route on every access, so it follows links, router.push and the browser's back button.

function useMoleculeQuery(): ComputedRef<QueryParams>

Returns: Reactive query params ref.

parseVueQuery(query)

Converts a Vue Router query object (with nullable values) into a molecule QueryParams object. Filters out null values and preserves arrays.

function parseVueQuery(
  query: Record<string, LocationQueryValue | LocationQueryValue[]>,
): QueryParams
  • query — The Vue Router LocationQuery object from route.query.

Returns: A molecule QueryParams map with only non-null values.

toVueQuery(params)

Converts a molecule QueryParams object to a Vue Router LocationQueryRaw object. Omits keys with undefined values.

function toVueQuery(params: QueryParams): LocationQueryRaw
  • params — The molecule query parameters.

Returns: A LocationQueryRaw compatible with Vue Router's router.push({ query }).

normalizeParams(params)

Normalizes Vue Router params (which may contain string | string[]) into molecule RouteParams (plain string values). Array values are joined with '/'.

function normalizeParams(params: Record<string, string | string[]>): RouteParams
  • params — The Vue Router params object from route.params.

Returns: A flat RouteParams map with string values only.

parseSearchParams(searchParams)

Converts URLSearchParams into QueryParams. A key that appears more than once becomes an array of its values, in order.

function parseSearchParams(searchParams: URLSearchParams): QueryParams
  • searchParams — The search params to read.

Returns: The query params.

stringifyQuery(params)

Serializes QueryParams into a query string with a leading ?, percent-encoding keys and values (a space is %20). Undefined values are left out; an array writes its key once per value.

function stringifyQuery(params: QueryParams): string
  • params — The query params.

Returns: The query string, or '' when there is nothing to write.

matchPath(pattern, pathname, exact)

Matches a route pattern against a pathname. :name captures one segment and * matches anything. The whole pathname must match unless exact is false, which also accepts a pathname that only starts with the pattern.

function matchPath<Params extends RouteParams = RouteParams>(
  pattern: string,
  pathname: string,
  exact?: boolean,
): RouteMatch<Params> | null
  • pattern — The pattern, such as /users/:id or /files/*.
  • pathname — The pathname to match.
  • exact — Whether the whole pathname must match (default true).

Returns: The match with its params, or null.

generatePath(pattern, params)

Builds a path from a pattern by putting each :name param in its place, percent-encoded. A pattern given no params is returned as it is.

function generatePath(pattern: string, params?: RouteParams): string
  • pattern — The pattern, such as /users/:id.
  • params — The param values.

Returns: The path.

resolvePath(to, fromPathname)

Resolves a path against the pathname it is relative to: an absolute to is returned as it is; otherwise to is joined to fromPathname's parent, with .. moving up and . staying.

function resolvePath(to: string, fromPathname: string): string
  • to — The path to resolve.
  • fromPathname — The pathname it is relative to.

Returns: The resolved pathname.

normalizePath(path)

Removes trailing slashes from a path, keeping / itself.

function normalizePath(path: string): string
  • path — The path.

Returns: The path without trailing slashes.

Constants

ListRouteNav

Render every declared list view as a router link. The URL selects the active choice, and selecting any view resets pagination through useListRoute. Native link behavior (new-tab clicks, keyboard activation and history) is preserved. This is a navigation landmark, not an ARIA tablist with local panels. No active-value state or change handler is needed. When children are supplied, they render after the navigation landmark. Put loading and empty results in that branch so a pending list never removes the filter controls.

The links are the component's OWN anchors: their href is the molecule router's createHref (the href the native router's own link writes, base path and hash history included), and a plain click navigates through followRouterLink, so a modified click, a target other than _self or an external URL is left to the browser. The rendered markup is exactly react-router's ListRouteNav: same elements, attributes and ARIA, no styles of its own. The accessible name and every other native attribute (id, class, listeners) arrive through Vue's attribute fallthrough onto the <nav>.

const ListRouteNav: DefineSetupFnComponent<
  ListRouteNavProps<string>,
  {},
  {},
  ListRouteNavProps<string> & {},
  PublicProps
>
  • props — Named destinations, translated labels, optional auth and native nav attributes.

Returns: The navigation landmark with all its choices, followed by any rendered content.

MoleculeRouterProvider

Provider component that builds ONE molecule Router over the current Vue Router and bonds it via @molecule/app-routing's setRouter, so navigate() / getRouter() from core drive the REAL Vue Router. It also provides that exact router under MOLECULE_ROUTER_KEY, so every descendant's useMoleculeRouter() returns it, and renders @molecule/app-vue's RouterProvider with it and Vue Router's RouterView as the routed view: @molecule/app-vue's routing composables read this router, and its RoutedView renders the matched child route in a layout or guard used as a route component. A MoleculeRouterProvider inside another one uses the outer one's router.

Bonding happens when the provider's setup runs, so core navigation reaches the native router for the provider's whole mounted life. onRouterReady fires once per router: a navigation or a re-render does not fire it again, and neither does changing only the callback.

const MoleculeRouterProvider: DefineComponent<
  ExtractPropTypes<{
    routes: { type: PropType<RouteDefinition[]>; default: undefined }
    onRouterReady: { type: PropType<(router: Router) => void>; default: undefined }
  }>,
  () => VNode,
  {},
  {},
  {},
  ComponentOptionsMixin,
  ComponentOptionsMixin,
  {},
  string,
  PublicProps,
  Readonly<
    ExtractPropTypes<{
      routes: { type: PropType<RouteDefinition[]>; default: undefined }
      onRouterReady: { type: PropType<(router: Router) => void>; default: undefined }
    }>
  > &
    Readonly<{}>,
  { routes: RouteDefinition[]; onRouterReady: (router: Router) => void },
  {},
  {},
  {},
  string,
  ComponentProvideOptions,
  true,
  {},
  any
>

MOLECULE_ROUTER_KEY

Injection key for the molecule Router a MoleculeRouterProvider provides to every component below it. useMoleculeRouter reads it first, so mounting the provider once makes each descendant composable return that exact router — with its named routes and its bond — instead of a router owned by the calling component.

A provided value is normally the provider's ComputedRef<Router>; a plain Router is accepted too, for an app that provides its adapter by hand.

const MOLECULE_ROUTER_KEY: InjectionKey<ComputedRef<Router> | Router | undefined>

provider

Default Vue Router provider (no Vue Router instance: the core's browser router). For the real Vue Router, use createVueRouter with useRouter — or the useMoleculeRouter* composables, which bond it for you.

const provider: Router

Core Interface

Implements @molecule/app-routing interface.

Bond Wiring

Setup function to register this provider with the core interface:

import { setRouter } from '@molecule/app-routing'
import { provider } from '@molecule/app-routing-vue-router'

export function setupRoutingVueRouter(): void {
  setRouter(provider)
}

Injection Notes

Requirements

Peer dependencies:

  • @molecule/app-bond ^1.0.1
  • @molecule/app-i18n ^1.0.1
  • @molecule/app-routing ^1.5.0
  • @molecule/app-vue ^3.10.0 || ^4.0.0
  • vue ^3.4.20
  • vue-router ^4.3.0 || ^5.0.0

Runtime Dependencies

  • @molecule/app-bond

  • @molecule/app-i18n

  • @molecule/app-routing

  • @molecule/app-vue

  • vue

  • vue-router

  • Use useMoleculeRouterProvider() once near the app root to bond the router. It builds the adapter from useRouter() and calls @molecule/app-routing's setRouter, so other molecule packages' navigate()/getRouter() drive the real Vue Router (SPA navigation). One Vue Router instance gets one molecule Router for the app's lifetime. useMoleculeRouter() (non-bonding) still exists for local use; if you only ever call that, molecule packages silently get the core's auto-created fallback browser router and navigate with full-page reloads.

  • Do NOT wire the exported provider const in a vue-router app — without a Vue Router instance it is the core's browser router, not Vue Router.

  • Composables must run inside a component tree that has the vue-router plugin installed (app.use(router)), since they call useRouter()/useRoute().

  • A route with parameters? Declare its page with defineRoute. The route path is the source of truth for the page's parameter names: :name, :name?, :name(regex), :name+ and :name* each arrive as string | undefined (a repeated parameter is joined with /). For example:

    import { h } from 'vue'
    import { defineRoute } from '@molecule/app-routing-vue-router'
    
    const routes = [
      defineRoute('/shelves/:shelf', ({ shelf }) => h(Shelf, { name: shelf, view: 'all' })),
      defineRoute('/shelves/:shelf/saved', ({ shelf }) => h(Shelf, { name: shelf, view: 'saved' })),
    ]