@molecule/app-routing-vue-router
v1.0.1
Published
Vue Router provider for @molecule/app-routing
Readme
@molecule/app-routing-vue-router
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.tsJSDoc, not this file.
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.
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-i18n @molecule/app-routing vue vue-routerAPI
Interfaces
NavigateOptions
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[]
}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
}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.
*/
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
/**
* Subscribes to route changes.
*/
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
Configuration options for creating a router instance.
interface RouterConfig {
/**
* Router mode.
*/
mode?: 'history' | 'hash' | 'memory'
/**
* Base path.
*/
basePath?: string
/**
* Initial routes.
*/
routes?: RouteDefinition[]
}VueRouterComposable
Vue Router composable return type.
interface VueRouterComposable {
/**
* Vue Router instance.
*/
router: VueRouterInstance
/**
* Current route.
*/
route: RouteLocationNormalizedLoaded
}VueRouterConfig
Vue Router-specific configuration.
interface VueRouterConfig {
/**
* Vue Router instance (from useRouter).
*/
router?: VueRouterInstance
/**
* Current route (from useRoute).
*/
route?: RouteLocationNormalizedLoaded
/**
* Initial route definitions for named routes.
*/
routes?: RouteDefinition[]
}Types
GuardResult
Navigation guard result.
type GuardResult =
| boolean
| string
| {
path: string
replace?: boolean
}
| voidNavigationGuard
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>QueryParams
URL query string parameter map (single values or arrays for repeated keys).
type QueryParams = Record<string, string | string[] | undefined>RouteChangeListener
Callback invoked on each route change with the new location and the navigation action that triggered it.
type RouteChangeListener = (location: RouteLocation, action: 'push' | 'replace' | 'pop') => voidRouteParams
URL path parameter key-value map extracted from dynamic route segments (e.g. { id: '123' }).
type RouteParams = Record<string, string>Functions
createVueRouter(config)
Creates a Vue Router adapter that implements the molecule Router interface.
function createVueRouter(config?: VueRouterConfig): Routerconfig— Configuration with Vue Router'srouterinstance, currentroute, and optionalroutes.
Returns: A molecule Router with navigation, guards, query/hash management, and route matching.
generatePath(pattern, params)
Generates a concrete path from a route pattern by replacing :param segments with values.
Throws if a required param is missing.
function generatePath(pattern: string, params?: RouteParams): stringpattern— The route pattern (e.g.'/users/:id').params— A map of param names to values.
Returns: The resolved path string with params URL-encoded.
matchPath(pattern, pathname, exact)
Matches a path pattern (with :param segments and * wildcards) against a pathname.
function matchPath(pattern: string, pathname: string, exact?: boolean): RouteMatch<Params> | nullpattern— The route pattern (e.g.'/users/:id').pathname— The actual URL pathname to test.exact— Whether to require an exact match (defaulttrue). Set tofalsefor prefix matching.
Returns: A RouteMatch with extracted params, or null if no match.
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[]>): RouteParamsparams— The Vue Router params object fromroute.params.
Returns: A flat RouteParams map with string values only.
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[]>,
): QueryParamsquery— The Vue RouterLocationQueryobject fromroute.query.
Returns: A molecule QueryParams map with only non-null values.
stringifyQuery(params)
Converts a molecule QueryParams object to a URL search string (e.g. ?key=val&arr=1&arr=2).
Omits keys with undefined values.
function stringifyQuery(params: QueryParams): stringparams— The query parameters to stringify.
Returns: A URL search string starting with ?, or empty string if no params.
toVueQuery(params)
Converts a molecule QueryParams object to a Vue Router LocationQueryRaw object.
Omits keys with undefined values.
function toVueQuery(params: QueryParams): LocationQueryRawparams— The molecule query parameters.
Returns: A LocationQueryRaw compatible with Vue Router's router.push({ query }).
useIsActive(path, exact)
Composable to check if a path is active.
function useIsActive(path: string, exact?: boolean): ComputedRef<boolean>path— Path to checkexact— Whether to require exact match
Returns: Reactive boolean ref
useLocation()
Composable to get the current location as a reactive ref.
function useLocation(): ComputedRef<RouteLocation>Returns: Reactive location ref
useMoleculeRouter(routes)
Composable to create and provide a molecule Router.
function useMoleculeRouter(routes?: RouteDefinition[]): ComputedRef<Router>routes— Optional route definitions for named routes
Returns: The molecule Router instance
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). It watches the
adapter with { immediate: true }, so setRouter runs synchronously in setup and
re-runs whenever the route changes — meaning @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).
useNavigate()
Composable to get a navigate function.
function useNavigate(): (path: string, options?: { replace?: boolean; state?: unknown }) => voidReturns: Navigate function
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>,
): voidguard— Guard function
useParams()
Composable to get route params as a reactive ref.
function useParams(): ComputedRef<T>Returns: Reactive params ref
useQuery()
Composable to get query params as a reactive ref.
function useQuery(): ComputedRef<QueryParams>Returns: Reactive query params ref
useRouteChange(callback)
Composable to subscribe to route changes.
function useRouteChange(
callback: (location: RouteLocation, action: 'push' | 'replace' | 'pop') => void,
): voidcallback— Callback to run on route change
Constants
MOLECULE_ROUTER_KEY
Symbol for providing molecule router in Vue.
const MOLECULE_ROUTER_KEY: typeof MOLECULE_ROUTER_KEYprovider
Default Vue Router provider (basic, no hooks). For full functionality, use
createVueRouter with useRouter/useRoute.
const provider: RouterCore 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-i18n^1.0.1@molecule/app-routing^1.0.1vue^3.4.0vue-router^4.3.0
Runtime Dependencies
@molecule/app-i18n@molecule/app-routingvuevue-routerUse
useMoleculeRouterProvider()once near the app root to bond the router. It builds the adapter fromuseRouter()/useRoute()and calls@molecule/app-routing'ssetRouterin an{ immediate: true }watch, so other molecule packages'navigate()/getRouter()drive the real Vue Router (SPA navigation).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
providerconst in a vue-router app — it is a no-hooks fallback (empty params,window.location.hrefnavigation).Composables must run inside a component tree that has the vue-router plugin installed (
app.use(router)), since they calluseRouter()/useRoute().
