useRouter()
useRouter(): Router returns the Router instance in the current context; it is the standard way to access the router in the Composable API.
ts
import { useRouter } from '@meng-xi/unix-router'
const router = useRouter()Instance Resolution Order
useRouter() resolves the router instance in the following order:
- Inject first inside setup: when inside a component's
setup(orscript setup), it first reads the routerprovided byapp.use(router)on the H5 side. In multi-instance scenarios, a component gets the nearest installed instance. - Fall back to the global active router when
injectis empty or outside setup: in option-stylemethods, event callbacks, and other non-setup contexts (whereinjectis unavailable), or when nothing was injected insidesetup, it falls back to the globally registered active router (the instance registered by the most recentapp.use(router)). - Throw when neither exists: if it is neither injected nor installed, it throws —
未找到路由器实例,请先 app.use(router) 后再调用 useRouter()("router instance not found; callapp.use(router)beforeuseRouter()").
What app.use(router) Does
router.install(app) is triggered by app.use(router):
- H5 (Web): registers
provide(foruseRouterinjection inside setup), mounts the$router/$routeglobal properties, and registers theonShowglobal mixin (which callsrouter.syncRoute()automatically). - Native platforms (App / Mini Program): registers the global active router for
useRouter()'s non-setup fallback; it is recommended to callrouter.syncRoute()manually in each page'sonShow.
On both platforms the plugins' app-level hook (onAppInstall) is triggered.
Usage in Components
vue
<script setup lang="uts">
import { useRouter } from '@meng-xi/unix-router'
const router = useRouter()
const goAbout = (): void => {
router.push({ name: 'about', query: new Map<string, string>([['from', 'home']]) })
}
</script>
<template>
<view class="page" @click="goAbout">
<text>Go to About</text>
</view>
</template>Notes
- It relies on
app.use(router)having installed the router; otherwise it throws (no usable instance exists before installation). - It is the same instance as the globally exported
router(single-instance scenarios); in multi-instance scenarios the injected result inside setup takes precedence.
